函數(shù)和閉包
Usefuncto declare a function. Call a function by following its name with a list of arguments in parentheses.
Use->to separate the parameter names and types from the function’s return type.
使用func來(lái)聲明一個(gè)函數(shù)赔硫,使用名字和參數(shù)來(lái)調(diào)用函數(shù)段磨。使用->來(lái)指定函數(shù)返回值的類(lèi)型臭笆。
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", day: "Tuesday")
EXPERIMENT
Remove thedayparameter. Add a parameter to include today’s lunch special in the greeting.
練習(xí): 刪除day參數(shù)官帘,添加一個(gè)參數(shù)來(lái)表示今天吃了什么午飯迷郑。使用元組來(lái)讓一個(gè)函數(shù)返回多個(gè)值嘿般。該元組的元素可以用名稱(chēng)或數(shù)字來(lái)表示靴姿。
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics([5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)
Functions can also take a variable number of arguments, collecting them into an array.
函數(shù)可以帶有可變個(gè)數(shù)的參數(shù)魂仍,這些參數(shù)在函數(shù)內(nèi)表現(xiàn)為數(shù)組的形式:
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
EXPERIMENT
Write a function that calculates the average of its arguments.
練習(xí): 寫(xiě)一個(gè)計(jì)算參數(shù)平均值的函數(shù)拐辽。
Functions can be nested. Nested functions have access to variables that were declared in the outer function.
You can use nested functions to organize the code in a function that is long or complex.
函數(shù)可以嵌套。被嵌套的函數(shù)可以訪問(wèn)外側(cè)函數(shù)的變量擦酌,你可以使用嵌套函數(shù)來(lái)重構(gòu)一個(gè)太長(zhǎng)或者太復(fù)雜的函
數(shù)俱诸。
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
Functions are a first-class type. This means that a function can return another function as its value.
函數(shù)是第一等類(lèi)型,這意味著函數(shù)可以作為另一個(gè)函數(shù)的返回值赊舶。
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
A function can take another function as one of its arguments.
函數(shù)也可以當(dāng)做參數(shù)傳入另一個(gè)函數(shù)睁搭。
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, condition: lessThanTen)
Functions are actually a special case of closures: blocks of code that can be called later. The code in a closure
has access to things like variables and functions that were available in the scope where the closure was
created, even if the closure is in a different scope when it is executed—you saw an example of this already
with nested functions. You can write a closure without a name by surrounding code with braces ({}). Useinto
separate the arguments and return type from the body.
函數(shù)實(shí)際上是一種特殊的閉包:它是一段能之后被調(diào)取的代碼。閉包中的代碼能訪問(wèn)閉包所建作用域中能得到的變
量和函數(shù)笼平,即使閉包是在一個(gè)不同的作用域被執(zhí)行的 - 你已經(jīng)在嵌套函數(shù)例子中所看到园骆。你可以使用{}來(lái)創(chuàng)建
一個(gè)匿名閉包。使用in將參數(shù)和返回值類(lèi)型聲明與閉包函數(shù)體進(jìn)行分離寓调。
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
EXPERIMENT
Rewrite the closure to return zero for all odd numbers.
練習(xí): 重寫(xiě)閉包锌唾,對(duì)所有奇數(shù)返回0。
You have several options for writing closures more concisely. When a closure’s type is already known, such as
the callback for a delegate, you can omit the type of its parameters, its return type, or both. Single statement
closures implicitly return the value of their only statement.
有很多種創(chuàng)建更簡(jiǎn)潔的閉包的方法夺英。如果一個(gè)閉包的類(lèi)型已知鸠珠,比如作為一個(gè)回調(diào)函數(shù),你可以忽略參數(shù)的類(lèi)型
和返回值秋麸。單個(gè)語(yǔ)句閉包會(huì)把它語(yǔ)句的值當(dāng)做結(jié)果返回渐排。
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
You can refer to parameters by number instead of by name—this approach is especially useful in very short
closures. A closure passed as the last argument to a function can appear immediately after the parentheses.
When a closure is the only argument to a function, you can omit the parentheses entirely.
你可以通過(guò)參數(shù)位置而不是參數(shù)名字來(lái)引用參數(shù)——這個(gè)方法在非常短的閉包中非常有用。當(dāng)一個(gè)閉包作為最后
一個(gè)參數(shù)傳給一個(gè)函數(shù)的時(shí)候灸蟆,它可以直接跟在括號(hào)后面驯耻。當(dāng)一個(gè)閉包是傳給函數(shù)的唯一參數(shù),你可以完全忽略
括號(hào)炒考。
let sortedNumbers = numbers.sort { $0 > $1 }
print(sortedNumbers)