38

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.

rmaddy
  • 307,833
  • 40
  • 508
  • 550
Leem
  • 15,772
  • 32
  • 101
  • 149
  • Compare https://stackoverflow.com/questions/24035648/swift-and-mutating-struct. – Martin R Mar 13 '18 at 10:11
  • 1
    Or directly from the Swift documentation https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html: *"Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods. However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method."* – Martin R Mar 13 '18 at 10:11

2 Answers2

62

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)

Dixit Akabari
  • 2,243
  • 11
  • 24
1

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

stevenpcurtis
  • 1,803
  • 2
  • 19
  • 42