Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - How to mutate a struct object when iterating over it

I am still not sure about the rules of struct copy or reference.

I want to mutate a struct object while iterating on it from an array: For instance in this case I would like to change the background color but the compiler is yelling at me

struct Options {
  var backgroundColor = UIColor.blackColor()
}

var arrayOfMyStruct = [MyStruct]

...

for obj in arrayOfMyStruct {
  obj.backgroundColor = UIColor.redColor() // ! get an error
}
like image 705
Avner Barr Avatar asked Apr 21 '15 16:04

Avner Barr


2 Answers

struct are value types, thus in the for loop you are dealing with a copy.

Just as a test you might try this:

Swift 3:

struct Options {
   var backgroundColor = UIColor.black
}

var arrayOfMyStruct = [Options]()

for (index, _) in arrayOfMyStruct.enumerated() {
   arrayOfMyStruct[index].backgroundColor = UIColor.red
}

Swift 2:

struct Options {
    var backgroundColor = UIColor.blackColor()
}

var arrayOfMyStruct = [Options]()

for (index, _) in enumerate(arrayOfMyStruct) {
    arrayOfMyStruct[index].backgroundColor = UIColor.redColor() 
}

Here you just enumerate the index, and access directly the value stored in the array.

Hope this helps.

like image 124
Matteo Piombo Avatar answered Nov 13 '22 16:11

Matteo Piombo


You can use use Array.indices:

for index in arrayOfMyStruct.indices {
    arrayOfMyStruct[index].backgroundColor = UIColor.red
}
like image 24
emlai Avatar answered Nov 13 '22 16:11

emlai