Learning from the Geek Academy: functions in Swift
Tool: Xcode6.4
Directly on the basis of the sample code, more knocks more experience will have a harvest: hundred see not like a knock, a knock will
1 Import Foundation2 3 /*********** nested function *************/4Func Getmathfunc (#type: String), (INT)int{5Func squre (Num:int)int{6 returnnum*Num7 }8Func Cube (num:int)int{9 returnnum*num*NumTen } One Switch(type) { A Case "Square": - returnsqure - default: the returnCube - } - } -var mathfunc = Getmathfunc (type:" Other") +println (Mathfunc (4)) - //because nested functions only work inside the function inside the outer function, using closures simplifies this nested function + A /*********** Closure Package *************/ at /* - {(formal parameter list)--(return value) in - Executable Statements - } - */ -Func getmathfunc_1 (#type: String), (INT)int{ in //func squre (num:int), int{ - //return Num*num to // } + //func Cube (num:int), int{ - //return Num*num*num the // } * Switch(type) { $ Case "Square":Panax Notoginseng return { -(Num:int), Intinch the returnNum *Num + } A default: the return { +(Num:int)->intinch - returnnum * num *Num $ } $ } - } -var mathfunc_1 = getmathfunc_1 (type:" Other") theprintln (Mathfunc_1 (5)) - //infer types with contextWuyivar squre1: (int), int = {(num)inch returnnum*num} theprintln (Squre1 (8)) -var squre2: (int), int = {numinch returnnum*num} Wuprintln (Squre2 (9)) - //omit formal parameter name, by $0,$1 ... to reference the first, second argument Aboutvar squre3: (int), int = {$0* $0} $println (Squre3 (Ten)) - - //The classic use of closures -var result:int = { Avar result =1 + forIinch 1...$1{ theResult *= $0 - } $ returnresult the}(4,3) the println (Result) the the //trailing closures -Func someFunction (NUM:INT,FN: (INT)()){ in //Execute Code the}//The first parameter is an integer and the second parameter is a closure the //Call this function: SomeFunction (20,{}) About //format for calling functions with trailing closures: someFunction {} the the //a variable or constant in the capture context theFunc Makearr (ele:string),[string]{ + //Create an array that does not contain any elements -var arr: [String] = [] theFunc addelement ()[string]{Bayi //adds an element to the ARR array the arr.append (ele) the returnarr - } - returnaddelement the}
Functions in Swift (bottom)