//function Basic DefinitionFunc function name (parameter name: argument type = default value)return value type {code block}//No parameter no return value functionfunc hsmin () {}//single parameter no return value functionfunc Prin (st:string) {println (ST)}prin ("111")//111func Yuanzu (tup: (String,int)) {Print ("int:\ (TUP.1) string:\ (tup.0)")}yuanzu ("Feng Xiaogang",1))//int:1 String: Feng Xiaogang//Multi-parameter no return value functionfunc ADDP (a:int,b:int) {println (\ (a+b))} ADDP (1,2)//3//single parameter return value functionFunc prt (l:int)int{returnL +1}println ("\ (PRT (2)")//3//Multi-parameter return value functionFunc Add (A:int, B:int),int{returnA +B}func del (a:int, B:int)-int{returnA-b}println (Add (3,4))//7//parameter Default valueFunc sum (a:int, b:int =1),int{returnA +b}println (SUM (3))//4//Output Parametersfunc swaptwoints (inout a:int, inout b:int) {Let Temporarya=a A=b b=Temporarya}var Someint=3var anotherint=107swaptwoints (&someint, &anotherint) println ("Someint is now \ (Someint), and Anotherint are now \ (anotherint)")//function Nesting (anonymous function)Func choosestepfunction (Backwards:bool), (INT)Int {func stepforward (input:int)-Int {returnInput +1} func Stepbackward (input:int)-Int {returnInput-1 } returnBackwards?Stepbackward:stepforward}var CurrentValue= -4Let Movenearertozero= Choosestepfunction (CurrentValue >0)//Movenearertozero now refers to the nested Stepforward () function whileCurrentValue! =0{println ("\ (currentvalue) ...") CurrentValue=Movenearertozero (CurrentValue)}println ("zero!")//-4 ...//-3 ...//-2 ...//-1 ...//zero!
Personal feeling closure (Closures) the equivalent of a block in C is just a re-improvement on block basis.
//the complete wording of closures{(parameter list), return typeinchcode block}//egvar A:array = [3,1,4,2,5,7,6]var b= Sort (A, {(I1:int, i2:int), BoolinchRetern i1>I2})//b=[1,2,3,4,5,6,7]//Swift Support type recognition is shortened tovar B = Sort (A, {i1, i2inchRetern i1>I2})//b=[1,2,3,4,5,6,7]//You can also use parameter recognition $0,$1var b = sort (a,{$0> $1})//b=[1,2,3,4,5,6,7]//No parameter no return value closureFunc somefunctionthattakesaclosure (Closure: ()()) {code block} somefunctionthattakesaclosure ({code block}) somefunctionthattakesaclosure () {code block}
Swift Basic Syntax (quad) function, Closure (Closures)