Swift 3.0中文版(3)函數(shù)和閉包

函數(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)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末可缚,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子斋枢,更是在濱河造成了極大的恐慌帘靡,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瓤帚,死亡現(xiàn)場(chǎng)離奇詭異描姚,居然都是意外死亡涩赢,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)轩勘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)筒扒,“玉大人,你說(shuō)我怎么就攤上這事绊寻』ǘ眨” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵澄步,是天一觀的道長(zhǎng)冰蘑。 經(jīng)常有香客問(wèn)我,道長(zhǎng)村缸,這世上最難降的妖魔是什么懂缕? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮王凑,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘聋丝。我一直安慰自己索烹,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布弱睦。 她就那樣靜靜地躺著百姓,像睡著了一般。 火紅的嫁衣襯著肌膚如雪况木。 梳的紋絲不亂的頭發(fā)上垒拢,一...
    開(kāi)封第一講書(shū)人閱讀 51,562評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音火惊,去河邊找鬼求类。 笑死,一個(gè)胖子當(dāng)著我的面吹牛屹耐,可吹牛的內(nèi)容都是我干的尸疆。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼惶岭,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼寿弱!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起按灶,我...
    開(kāi)封第一講書(shū)人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤症革,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后鸯旁,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體噪矛,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡量蕊,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了摩疑。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片危融。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖雷袋,靈堂內(nèi)的尸體忽然破棺而出吉殃,到底是詐尸還是另有隱情,我是刑警寧澤楷怒,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布蛋勺,位于F島的核電站,受9級(jí)特大地震影響鸠删,放射性物質(zhì)發(fā)生泄漏抱完。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一刃泡、第九天 我趴在偏房一處隱蔽的房頂上張望巧娱。 院中可真熱鬧,春花似錦烘贴、人聲如沸禁添。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)老翘。三九已至,卻和暖如春锻离,著一層夾襖步出監(jiān)牢的瞬間铺峭,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工汽纠, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留卫键,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓虱朵,卻偏偏與公主長(zhǎng)得像永罚,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子卧秘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 以下翻譯自Apple官方文檔呢袱,結(jié)合自己的理解記錄下來(lái)。翻譯基于 swift 3.0.1 原文地址 Closure...
    藝術(shù)農(nóng)閱讀 1,538評(píng)論 0 3
  • 86.復(fù)合 Cases 共享相同代碼塊的多個(gè)switch 分支 分支可以合并, 寫(xiě)在分支后用逗號(hào)分開(kāi)翅敌。如果任何模式...
    無(wú)灃閱讀 1,367評(píng)論 1 5
  • 君惟明氣息因此亦岔羞福,同樣撲倒在大桶邊緣。翠姨匆匆趕入蚯涮,瞧見(jiàn)兩人這副情形治专,暗暗叫苦卖陵。伸手去探君海棠胸口,面色大變张峰,“...
    十一鸞閱讀 287評(píng)論 0 1
  • 十一月的北國(guó)就開(kāi)始飄雪了泪蔫,這一天,我走在學(xué)校的小路上喘批,兩邊的樹(shù)高高矗立撩荣,光禿禿的枝椏就像是冰冷的雕塑,似乎萬(wàn)年未動(dòng)...
    最?lèi)?ài)睡覺(jué)的魚(yú)閱讀 358評(píng)論 1 2
  • 你眼中的我是怎么樣的我 現(xiàn)實(shí)中的我在不斷剝落 也許你認(rèn)為我已經(jīng)頹紕猙獰 但是我卻心急如焚地褪盡塵世殘骸 努力展示真...
    撐篙人閱讀 170評(píng)論 0 5