1 //Playground-noun:a Place where people can play2 3 ImportCocoa4 //functions and closures5 6 //function, declare the function using the Func keyword:7Func greet (name:string, day:string)String {8 return"Hello \ (name), today is \ (day)."9 }TenGreet ("Bob", "Tuesday") One A - //returning multiple values by tuple (tuple) -Func getgasprices ()(double, double, double) { the return(3.59, 3.69, 3.79) - } - getgasprices () - + //supports functions with variable-length parameters -Func sumof (Numbers:int ...)Int { +var sum = 0 A forNumber in numbers { atSum + = Number - } - returnsum - } - - sumof () inSumof (42, 597, 12) - to //functions can also be nested +Func Returnfifteen ()Int { -var y = 10 the func Add () { *Y + = 5 $ }Panax Notoginseng Add () - returny the } + A Returnfifteen () the + //as a first-class object, a function can either be a return value or be passed as a parameter - $Func makeincrementer (), IntInt) { $Func AddOne (Number:int)Int { - return1 + Number - } the returnAddOne - }Wuyivar increment =Makeincrementer () theIncrement (7) - WuFunc hasanymatches (list:int[], Condition:int-Bool)Bool { - foritem in list { About ifcondition (item) { $ return true - } - } - return false; A } + theFunc Lessthanten (Number:int)Bool { - returnNumber < 10 $ } thevar numbers = [20, 19, 7, 12] the hasanymatches (Numbers, Lessthanten) the the //closures-essentially, a function is a special closure, and Swift can use {} to declare anonymous closures - in Numbers.map ({ the(Number:int)Int in theLet result = 3 * Number About returnresult the }) the //when the type of closure is known, the following simplified notation can be used theNumbers.map ({number in 3 *Number }) + //parameters can also be used by the position of the parameter, and the following syntax can be used when the last parameter of the function is a closure: -Sort ([1, 5, 3, 2]) {$ > $}
Swift Basic Syntax III (functions and closures)