2

I have a struct like this

struct MyStruct {
  var name : String?
  var address : String?
  var affiliated : Bool?
}

and then an array of MyStruct

var myArray : [MyStruct]? ...

As soon as I create an array of MyStruct every element inside that array is non-mutating, right?

The problem is that at some point I have to scan that array and update a field of all elements, like updating affiliated for every element of myArray and this update is asynchronous.

This is my problem. All elements inside myArray are not mutating.

The way I would solve that was by recreating every MyStruct element with the new value for affiliated, recreating myArray and replacing the old array with this new one.

It seems a dumb method, a waste of time and effort.

Is there a better way to do this?

1 Answer 1

4

As soon as I create an array of MyStruct every element inside that array is non-mutating, right?

Not necessarily. But as arrays are value types you have to update an element of the array directly in the array for example

var myArray = [MyStruct(name: "Foo", address: nil, affiliated: false), MyStruct(name: "Bar", address: nil, affiliated: false)]

myArray[1].affiliated = true
print(myArray)
Sign up to request clarification or add additional context in comments.

1 Comment

Yep. Subscripts are Swift's way to encode l-values (lots of info on this from the C++ world).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.