2

I have a swift array of struct and I am unable edit the first property, whereas I am able edit the first property with an array of class.

In order to edit the first object of the struct array, I have to do [0] then .first

I know structs are valued by type, class are value by reference. But I don't understand the different behavior. Can someone explain?

class PersonObj {
    var name = "Dheearj"

}

struct Person  {
    var name = "Dheearj"
    
    mutating func update(name: String){
        self.name = name
    }
}

var array = [Person(),Person()]
array[0].update(name:"dheeraj")
array[0].name = "yuuu"
array.first?.name = "dddddd" <--- "Error Here"

var array1 = [PersonObj(),PersonObj()]
array1.first!.name = "ttt"

print(array1.first?.name ?? "")
print(array.first?.name ?? "")
print(array.count)

Screenshot of the error message:

enter image description here

1 Answer 1

4

Mutating a struct stored within some other property behaves as though you've copied out the value, modified it, and overwrote it back into place.

Take this line for example: (I replaced the optional chaining with force unwrapping, for simplicity)

array.first!.name = "dddddd"

It behaves as though you did:

var tmp = array.first!
tmp.name = "dddddd"
array.first = tmp

It's easy to see what that doesn't work. Array.first, is a get-only property (it doesn't have a setter).

The case for classses works because the value stored in the array is a reference to the object, and the reference isn't changing (only the values within the object it refers to, which the array doesn't know or care about).

Sign up to request clarification or add additional context in comments.

Comments

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.