注意:Swift除了..还有…:..生成前闭后开的区间,而…生成前闭后闭的区间。
3.函数和闭包
3.1函数
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








