In Swift , there are three types (type): structure,enumeration,class
where structure and enumeration are value types (value type), class is a reference type (reference )
However, unlike OBJECTIVE-C, structure and enumeration can also have methods, where methods can be instance methods (instance method) or class methods (type method). An instance method is bound to an instance of the type.
In the swift official tutorial There is this sentence:
"Structures and enumerations is value types. By default, the properties of a value type cannot is modified from within its instance methods. " Excerpt from: Apple Inc. "The Swift programming Language". IBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329
The general meaning is that although structs and enumerations can define their own methods, by default, the instance method is not able to modify the value type's properties.
As a simple example, if you define a point structure, the struct has an instance method that modifies the point location:
struct Point { var x = 0, y = 0 func movexby (x:int,yby y:int) { self.x + = x //cannot invoke ' + = ' with an argument list of type ' (int, int) ' self.y + = y //cannot invoke ' + = ' with an argument list of type ' (int, int) '
}}
The compiler throws an error stating that the property value cannot be modified in the instance method.
To be able to modify property values in an instance method, you can add a keyword before the method definition mutating
struct Point { var x = 0, y = 0 mutating func movexby (x:int,yby y:int) { self.x + = x self.y + = y } }var p = Point (X:5, Y:5) P.movexby (3, Yby:3)
In addition, the Self property value can also be modified directly in an instance method of a value type.
Enum Tristateswitch {case -off, low, high mutating func-Next () { switch self {case off: self = low
case Low: "Self = high ": Self = Off } }}var ovenlight = TriStateSwitch.LowovenLight.next ()//ovenlight is today equal to. Highovenlight.next ()//ovenlight is today equal to. Off "
The Tristateswitch enumeration defines a three-state switch that dynamically changes the value of the Self property in the next instance method.
Of course, the method in the reference type (that is, class) can modify the property value by default, without the above problem.
[Reference: The Swift programming Language] from IBook
Finally, I want to ask you a question, Learn swift that strong?
Swift's mutating keyword