IOS_Swift _ Better understanding of the difference between closures and lazy loading and normal assignment
To define a variable of a string:
// Directly assign var str = "JobDeer" // closure mode var str: String = {return "JobDeer"} () // simplify the closure, omitting equal signs and parentheses: var str: String {return "JobDeer "}
// The get and set methods can be defined in the closure. Var str: String {get {return "JobDeer"} set {println ("set OK") }}// note that willSet/didSet cannot be used together with get/set, when using willSet/didSet, the variable must have an initial value. So use this: var str: String = "JobDeer" {willSet {println ("newValue: \ (newValue)")} didSet {println ("oldValue: \ (oldValue) ")} str =" new value"
// The most complete definition format is {(arguments)-> returnType in code} (arguments) var str = {(arg1: String, arg2: String) -> String in return arg1 + arg2;} ("Job", "Deer") // based on the most comprehensive definition method above, can I omit the parameter type: var str = {arg1, arg2-> String in return arg1 + arg2;} ("Job", "Deer") // derivation of the swift type, the parameter type can be automatically determined based on the parameter passing in brackets. // Then we can omit the return value type var str: String = {arg1, arg2 in return arg1 + arg2;} ("Job", "Deer") in the closure ") // continue to simplify var str: String = {return $0 + $1;} ("Job", "Deer") // if the closure contains only one line of code, return can also be omitted. Var str: String = {$0 + $1;} ("Job", "Deer") // if the closure does not have a defined parameter, var str: string = {return "JobDeer"} () // no parameters are passed in brackets. You can omit the brackets. when parentheses are omitted, the equal sign cannot be var str: String {return "JobDeer "}
///// Normal value assignment var I = 0var up: Int? {I = I + 1 return I} for _ in 0... 2 {print ("--> \ (up !) ")} // --> 1 // --> 2 // --> 3 // closure execution, I added // load var id = 10 class Animal {lazy var addID: Int? = {Id ++ return id} () init () {}} let anim = Animal () print (anim. addID !) Print (anim. addID !) // 11 // 11 // the closure is executed, and anim. addID is not added again