Object-C ---) Swift (10) Storage attributes
The calculation attribute is equivalent to the getter and setter attributes of Object-C. In Swift, struct and classes can define calculation attributes.
Define computing attributes
[Modifier] var Calculation attribute name: attribute type {get {// getter method execution body, this method must have a return value} [set (form parameter name) {// setter method execution body, which must not return values}]}
Note: The var Calculation attribute can only be defined as a variable.
Enum Season {case Spring, Summer, Fall, Wintervar info: String {get {print ("The getter method is being executed") switch (self) {case. spring: return "Spring blossom"} default: return "permanent"} set (newValue) {print ("the setter method is being executed, and the input parameter is \ (newValue) ") }}var s = Season. springprint (s.info) // access the info attribute, which is actually to call the corresponding getter method s.info = "" // assign a value to the info attribute, which is actually to call the corresponding setter method}
Another example of a class
Class User {var first: String = "" var last: String = "" var fullName: String {get {return first + "-" + last} set (newValue) {var names = newValue. componentsSeparatedByString ("-") self. first = names [0] self. last = name [1]} init (first: String, last: String) {self. first = first self. last = last} let s = User (first: "小 ", last: "Sun Wukong") print (s. fullName) s. fullName =" Zi Dan-Wukong" print (s. first) // output vertex print (s. last) // output Wukong
Simplified setter Method
The setter method for calculating an attribute always has only one parameter, and the parameter type is the same as the type of this calculation attribute. Therefore, Swift allows you to omit the parameter names in the set part when defining the calculation attribute.
If the program omitted the parameter name of the set part of the calculation attribute, the program will provide this parameter with an implicit Parameter Name: newValue. So you can change it
set{ var names=newValue.componentsSeparatedByString("-") self.first=name[0] self.last=name[1]}
Read-Only computing attributes
Only the get part is called the read-only computing attribute. We can omit the get keyword and curly braces.
The above can be changed
var fullName:String{ return first + "-" + last }
Note that even the read-only attribute must use the var keyword.