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.
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)
Because a Struct is a value type, and therefore should be immutable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With