Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign to property: 'self' is immutable, I know how to fix but needs understanding

Tags:

swift

I have a struct :

public struct MyStruct {   public var myInt: Int = 0   ... } 

I have a extension of MyStruct:

extension MyStruct {    public func updateValue(newValue: Int) {      // ERROR: Cannot assigned to property: 'self' is immutable      self.MyInt = newValue   } } 

I got the error showing above, I know I can fix the error by several ways, e.g. add a mutating keyword before func.

I am here not asking how to fix the error, but ask why swift doesn't allow this kind of value assignment ? I need an explanation besides a fix.

like image 261
Leem Avatar asked Mar 13 '18 10:03

Leem


2 Answers

struct is a value type. For value types, only methods explicitly marked as mutating can modify the properties of self, so this is not possible within a computed property.

If you change struct to be a class then your code compiles without problems.

Structs are value types which means they are copied when they are passed around.So if you change a copy you are changing only that copy, not the original and not any other copies which might be around.If your struct is immutable then all automatic copies resulting from being passed by value will be the same.If you want to change it you have to consciously do it by creating a new instance of the struct with the modified data. (not a copy)

like image 165
Dixit Akabari Avatar answered Sep 22 '22 00:09

Dixit Akabari


Because a Struct is a value type, and therefore should be immutable

like image 31
stevenpcurtis Avatar answered Sep 23 '22 00:09

stevenpcurtis