Swift 整理(四)——控制流、函數(shù)莲组、閉包

  • 控制流:for-in暖夭、while、Repeat-While竭望、if裕菠、switch
 let someCharacter: Character = "z"
 switch someCharacter {
case "a":
     print("The first letter of the alphabet")
 case "z":
     print("The last letter of the alphabet")
 default:
     print("Some other character")
}
// 輸出 "The last letter of the alphabet"
let anotherCharacter: Character = "a"
 switch anotherCharacter {
 case "a", "A":
     print("The letter A")
 default:
     print("Not the letter A")
 }
// 輸出 "The letter A
let approximateCount = 62
 let countedThings = "moons orbiting Saturn"
 var naturalCount: String
 switch approximateCount {
 case 0:
     naturalCount = "no"
 case 1..<5:
     naturalCount = "a few"
 case 5..<12:
     naturalCount = "several"
 case 12..<100:
     naturalCount = "dozens of"
 case 100..<1000:
     naturalCount = "hundreds of"
 default:
     naturalCount = "many"
 }
print("There are \(naturalCount) \(countedThings).") // 輸出 "There are dozens of moons orbiting Saturn."
//元組
 let somePoint = (1, 1)
 switch somePoint {
 case (0, 0):
     print("(0, 0) is at the origin")
 case (_, 0):
     print("(\(somePoint.0), 0) is on the x-axis")
 case (0, _):
     print("(0, \(somePoint.1)) is on the y-axis")
 case (-2...2, -2...2):
     print("(\(somePoint.0), \(somePoint.1)) is inside the box")
 default:
     print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
 }
// 輸出 "(1, 1) is inside the box"
//值綁定:
let anotherPoint = (2, 0)
 switch anotherPoint {
 case (let x, 0):
     print("on the x-axis with an x value of \(x)")
 case (0, let y):
     print("on the y-axis with a y value of \(y)")
 case let (x, y):
     print("somewhere else at (\(x), \(y))")
 }
// 輸出 "on the x-axis with an x value of 2"
//用where
 let yetAnotherPoint = (1, -1)
 switch yetAnotherPoint {
 case let (x, y) where x == y:
     print("(\(x), \(y)) is on the line x == y")
 case let (x, y) where x == -y:
     print("(\(x), \(y)) is on the line x == -y")
 case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
// 輸出 "(1, -1) is on the line x == -y"
//貫穿:和C語言一樣執(zhí)行下一個case
let integerToDescribe = 5
 var description = "The number \(integerToDescribe) is"
 switch integerToDescribe {
 case 2, 3, 5, 7, 11, 13, 17, 19:
     description += " a prime number, and also"
     fallthrough
 default:
     description += " an integer."
 }
print(description)
// 輸出 "The number 5 is a prime number, and also an integer."
  • 轉(zhuǎn)移語句:continue旧烧、break萤彩、fallthrough、return杖小、throw、guard-else
    continue:繼續(xù)執(zhí)行下一次循環(huán)
    break:結(jié)束循環(huán)
    fallthrough:貫穿昂勉,在switch中扫腺,可以執(zhí)行下一個case
    return:返回函數(shù)
    throw:錯誤拋出
    guard-else:提前退出
//標(biāo)簽:
 gameLoop: while square != finalSquare {
     diceRoll += 1
     if diceRoll == 7 { diceRoll = 1 }
     switch square + diceRoll {
     case finalSquare:
// 骰子數(shù)剛好使玩家移動到最終的方格里笆环,游戲結(jié)束。
         break gameLoop
     case let newSquare where newSquare > finalSquare:
// 骰子數(shù)將會使玩家的移動超出最后的方格迫吐,那么這種移動是不合法的账忘,玩家需要重新擲骰子
         continue gameLoop
     default:
// 合法移動,做正常的處理 square += diceRoll
square += board[square]
} }
 print("Game over!")
  • 函數(shù):func 是一段完成特定任務(wù)的獨立代碼片段溉浙。
//可選元組返回類型
func minMax(array: [Int]) -> (min: Int, max: Int)? {
     if array.isEmpty { return nil }
     var currentMin = array[0]
     var currentMax = array[0]
     for value in array[1..<array.count] {
         if value < currentMin {
             currentMin = value
         } else if value > currentMax {
             currentMax = value
         }
}
     return (currentMin, currentMax)
 }
//
 if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
     print("min is \(bounds.min) and max is \(bounds.max)")
}
// 打印 "min is -6 and max is 109"
//
//可變參數(shù)的func(1個戳稽、2個期升、3個....)
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)
// 返回 3.0, 是這 5 個數(shù)的平均數(shù)。 arithmeticMean(3, 8.25, 18.75)
// 返回 10.0, 是這 3 個數(shù)的平均數(shù)赊时。
//
//函數(shù)類型作為參數(shù)類型:
func stepForward(_ input: Int) -> Int {
     return input + 1
 }
 func stepBackward(_ input: Int) -> Int {
     return input - 1
 }
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
     return backward? stepBackward : stepForward
//用 chooseStepFunction(backward:) 來獲得兩個函數(shù)其中的一個
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero 現(xiàn)在指向 stepBackward() 函數(shù)行拢。
  • 閉包:自包含的函數(shù)代碼塊舟奠。
    三種形式的閉包:
  • 全局函數(shù)是一個有名字但不會捕獲任何值的閉包
  • 嵌套函數(shù)是一個有名字并可以捕獲其封閉函數(shù)域內(nèi)值的閉包
  • 閉包表達(dá)式是一個利用輕量級語法所寫的可以捕獲其上下文中變量常量值的匿名閉包

閉包表達(dá)式:

//sorted方法:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
func backward(_ s1: String, _ s2: String) -> Bool {
    return s1 > s2
}
var reversedNames = names.sorted(by: backward)
// reversedNames 為 ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
//轉(zhuǎn)成閉包表達(dá)式:
 reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
     return s1 > s2
})
//根據(jù)上下文推斷類型
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
//單表達(dá)式閉包隱式返回
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )

尾隨閉包:

func someFunctionThatTakesAClosure(closure: () -> Void) { 
// 函數(shù)體部分
}
// 以下是不使用尾隨閉包進(jìn)行函數(shù)調(diào)用
someFunctionThatTakesAClosure(closure: {
// 閉包主體部分 
})
// 以下是使用尾隨閉包進(jìn)行函數(shù)調(diào)用
someFunctionThatTakesAClosure() {
// 閉包主體部分 
}

捕獲值:

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementer
}

逃逸閉包:@escaping

var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
    completionHandlers.append(completionHandler)
}

自動閉包:@autoclosure
一種自動創(chuàng)建的閉包沼瘫,用于包裝傳遞給函數(shù)作為參數(shù)的表達(dá)式。不接受任何參數(shù)湿故,當(dāng)它被調(diào)用的時候,會返回被包裝在其中的表達(dá)式的值脖阵。

//延時求值:
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] print(customersInLine.count)
// 打印出 "5"
let customerProvider = { customersInLine.remove(at: 0) } print(customersInLine.count)
// 打印出 "5"
print("Now serving \(customerProvider())!") // Prints "Now serving Chris!" print(customersInLine.count)
// 打印出 "4"
//
// customersInLine is ["Ewa", "Barry", "Daniella"]
 func serve(customer customerProvider: @autoclosure () -> String) {
     print("Now serving \(customerProvider())!")
 }
serve(customer: customersInLine.remove(at: 0)) // 打印 "Now serving Ewa!"
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末命黔,一起剝皮案震驚了整個濱河市就斤,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌搜立,老刑警劉巖槐秧,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件刁标,死亡現(xiàn)場離奇詭異址晕,居然都是意外死亡,警方通過查閱死者的電腦和手機启搂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門胳赌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來匙隔,“玉大人,你說我怎么就攤上這事纷责≡偕牛” “怎么了挺勿?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長喂柒。 經(jīng)常有香客問我不瓶,道長禾嫉,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任湃番,我火速辦了婚禮夭织,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘吠撮。我一直安慰自己尊惰,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布泥兰。 她就那樣靜靜地躺著,像睡著了一般鞋诗。 火紅的嫁衣襯著肌膚如雪膀捷。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天削彬,我揣著相機與錄音全庸,去河邊找鬼。 笑死融痛,一個胖子當(dāng)著我的面吹牛壶笼,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播雁刷,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼覆劈,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了沛励?” 一聲冷哼從身側(cè)響起责语,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎目派,沒想到半個月后坤候,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡企蹭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年铐拐,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片练对。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡遍蟋,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出螟凭,到底是詐尸還是另有隱情虚青,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布螺男,位于F島的核電站棒厘,受9級特大地震影響纵穿,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜奢人,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一谓媒、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧何乎,春花似錦句惯、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至各墨,卻和暖如春指孤,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背贬堵。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工恃轩, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人黎做。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓叉跛,卻偏偏與公主長得像,于是被迫代替她去往敵國和親引几。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354

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

  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile麗語閱讀 3,836評論 0 6
  • Swift 介紹 簡介 Swift 語言由蘋果公司在 2014 年推出挽铁,用來撰寫 OS X 和 iOS 應(yīng)用程序 ...
    大L君閱讀 3,213評論 3 25
  • 86.復(fù)合 Cases 共享相同代碼塊的多個switch 分支 分支可以合并, 寫在分支后用逗號分開伟桅。如果任何模式...
    無灃閱讀 1,366評論 1 5
  • Linux sed命令是利用script來處理文本文件。 sed可依照script的指令叽掘,來處理楣铁、編輯文本文件。 ...
    金星show閱讀 348評論 0 0
  • 這種黑白顛倒的生活方式已經(jīng)持續(xù)了半個月。每天從夕陽開始工作浓镜。凌晨四點的時候關(guān)掉房間的燈溃列,等待著日出,直到天空完全明...
    斯莫閱讀 207評論 0 1