swift的函数和scala的函数有区别,scala的每一个函数都是有返回值的
控制语句if,else也是一个函数,也是有返回值的
而swift不一样,swift的函数可以没有返回值,是有副作用的。
func sayHello(personName:String) -> String{ let greeting = "Hello, " + personName + "!" return greeting } println(sayHello("Anna")) println(sayHello("Brian")) func halfOpenRangeLength(start: Int,end:Int) -> Int{ return end - start } println(halfOpenRangeLength(1,10)) func count(string:String)->(vowels: Int,consonants: Int, others:Int){ var vowels = 0, consonants = 0, others = 0 for character in string{ switch String(character).lowercaseString{ case "a", "e", "i", "o", "u": ++vowels case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m","n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": ++consonants default: ++others } } return (vowels, consonants, others) } let total = count("some arbitrary string!") func join(string s1: String, toString s2: String, withJoiner joiner:String = "") -> String{ return s1 + joiner + s2 } join(string: "hello", toString: "world", withJoiner: ", ") func arithmeticMean(numbers: Double...) -> Double{ var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } arithmeticMean(1,2,3,4,5) func swapTwoInts(inout a:Int,inout b:Int){ let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherInt)
上面代码展示了swift里的函数常用方式,与参数定义,方式。
func addTwoInts(a: Int, b: Int) ->Int{ return a + b } var mathFunction: (Int,Int) -> Int = addTwoInts mathFunction(2,3) let anotherMathFunction = addTwoInts anotherMathFunction(1,2) func stepForward(input: Int) -> Int{ return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } func chooseStepFunction(backwards: Bool) -> (Int) -> Int{ return backwards ? stepBackward : stepForward } chooseStepFunction(true)(2) var currentValue = 3 while currentValue != 0 { println("\(currentValue)...") currentValue = chooseStepFunction(true)(currentValue) }
函数类型,swift里允许使用函数类型,说白了就是函数指针,或者C#里的委托。
var names = ["Chris","Alex","Ewa","Barry","Daniella"] func backwards(s1: String, s2: String) -> Bool { return s1 > s2 } sort(&names, backwards) sort(&names, { (s1: String, s2: String) -> Bool in return s1 > s2 }) sort(&names, {a,b in return a > b }) sort(&names, {a,b in a > b }) sort(&names, { $0 > $1 }) sort(&names) { $0 > $1 } sort(&names, >) let digitNames = [ 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" ] let numbers = [16, 58, 510] let strings = numbers.map{ (var number)-> String in var output = "" while number > 0 { output = digitNames[number % 10]! + output number /= 10 } return output }
以上是闭包,swift闭包语法上与scala,C#等差不多,也支持捕获外部变量