Function
Swift uses the func keyword to declare a function:
Func greet (name:string, day:string), String { return'Hello \ (name), today is \ ( Day). " }greet ("Bob""Tuesday")
Return multiple values by tuple (tuple):
Func getgasprices () (double, double, double ) {return (3.593.693.79 )}getgasprices ()
Supports functions with variable-length parameters, using an array to obtain them:
Func sumof (Numbers:int ...), Int {0for in Numbers { + = number } return sum}sumof () sumof (597 )
Functions can also be nested:
Func Returnfifteen (), Int { ten func Add () { 5 } Add () return y}returnfifteen ()
As a first-class object, a function can either be a return value or be passed as a parameter:
//do return valueFunc makeincrementer (), IntInt) {func AddOne (number:int)-Int {return 1+Number }returnAddone}var Increment=Makeincrementer () increment (7)//do the ParametersFunc hasanymatches (list:int[], Condition:int-Bool)Bool { forIteminchList {ifcondition (item) {return true } } return false}func Lessthanten (number:int)-Bool {returnNumber <Ten}var Numbers= [ -, +,7, A]hasanymatches (Numbers, Lessthanten)
Closed Package
Essentially, a function is a special closure, and Swift can declare anonymous closures with {}:
Numbers.map ({ in 3 * number return Result })
If a type of closure is known, such as a callback function, you can ignore the type and return value of the parameter. A single statement closure will return the value of its statement as a result.
inch 3 * number})
You can refer to parameters by parameter location instead of parameter name-this method is very useful in very short closures. When a closure is passed to a function as the last argument, it can be followed directly by the parentheses.
Sort ([1,5,3,2]) {$0>$1}
Closure is actually a type of Swift, writing (), then he can be nested as a parameter of func. Written like this:
140 func exec (repeat:int, Block: ()-> () 141 { 142 for i in 1 ...repeat{ 143 block () 144 145 146 147 exec (10 , {println ( " hello World )})
Swift also proposes a special term: Trailing Closures, which he means: if the closure is the last parameter of the Func, then he can write it out. As follows:
148Func exec (Repeat:int, Block: ()()) 149 { Max forIinch 1. .. repeat{151block () the } 153 } 154 155execTen){ 156println"Hello World") 157 }
Swift learns 2---functions and closures