A method for defining a variable of a string:
Direct assignment var str= "Jobdeer"//Closure mode var str:string={ return "Jobdeer"} ()//simplify closure, omit equals and parentheses: Var str:string{ return " Jobdeer "}
A get, set method can be defined in a closure. var str:string{ get{ return "Jobdeer" } set{ println ("set OK") }}//Note willset/ Didset cannot be used in conjunction with Get/set, the variable needs to have an initial value when using Willset/didset. So use: var str:string= "Jobdeer" { willset{ println ("Newvalue:\ (newvalue)") } didset{ println ("Oldvalue:\ (OldValue)") }} Str= "New Value"
//the most complete definition form is {(arguments)->returntype in code} (arguments) var str={(arg1:string,a rg2:string)->string in return arg1+arg2;} ("Job", "Deer")//based on the most complete definition above, I can omit the type of the parameter: Var str={arg1,arg2->string in return arg1+arg2;} ("Job", "Deer") the type derivation of//swift, which automatically determines the type of the parameter according to the arguments of the following parentheses. Then we can omit the return value type in the closure var str:string={arg1,arg2 in return arg1+arg2;} ("Job", "Deer")//continue to simplify Var str:string={return $0+$1;} ("Job", "Deer")//if there is only one line of code in the closure, return can also be omitted. var str:string={$0+$1;} ("Job", "Deer")//If the closure does not define a parameter, such as Var str:string={return "Jobdeer"} ()//The parentheses do not have arguments at all, you can omit the parentheses. An equal sign that omits parentheses does not write Var Str:strin g{return "Jobdeer"}
general assignment var i = 0var up:int? { i = i+1 return i}for _ in 0...2{ print ("-->\ (up!)")} -->1//-->2//-->3//closure execution, I add//////lazy load var id = 10class Animal { lazy var addid:int? = { id++ return ID } () init () { }}let anim = Animal () print (anim.addid!) Print (anim.addid!) 11//11//closure execution, Anim.addid did not increase again
Ios_swift_ in-depth understanding of the difference between lazy loading and normal assignment in closure comparison