Swift 使用func
关键字声明函数:
func greet (name: String, day: String) -> String { return "Hello \(name), today is \(day)." } greet ("Bob", "Tuesday")
通过元组(Tuple)返回多个值:
func getGasPrices () -> (Double, Double, Double) { return (3.59, 3.69, 3.79) } getGasPrices ()
支持带有变长参数的函数:
func sumOf (numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } sumOf () sumOf (42, 597, 12)
函数也可以嵌套函数:
func returnFifteen () -> Int { var y = 10 func add () { y += 5 } add () return y } returnFifteen ()
作为头等对象,函数既可以作为返回值,也可以作为参数传递:
func makeIncrementer () -> (Int -> Int) { func addOne (number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer () increment (7)
func hasAnyMatches (list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition (item) { return true } } return false } func lessThanTen (number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches (numbers, lessThanTen)