Swift 整理(四)——控制流、函數、閉包

  • 控制流: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語言一樣執行下一個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."
  • 轉移語句:continue、break、fallthrough、return、throw、guard-else
    continue:繼續執行下一次循環
    break:結束循環
    fallthrough:貫穿,在switch中,可以執行下一個case
    return:返回函數
    throw:錯誤拋出
    guard-else:提前退出
//標簽:
 gameLoop: while square != finalSquare {
     diceRoll += 1
     if diceRoll == 7 { diceRoll = 1 }
     switch square + diceRoll {
     case finalSquare:
// 骰子數剛好使玩家移動到最終的方格里,游戲結束。
         break gameLoop
     case let newSquare where newSquare > finalSquare:
// 骰子數將會使玩家的移動超出最后的方格,那么這種移動是不合法的,玩家需要重新擲骰子
         continue gameLoop
     default:
// 合法移動,做正常的處理 square += diceRoll
square += board[square]
} }
 print("Game over!")
  • 函數:func 是一段完成特定任務的獨立代碼片段。
//可選元組返回類型
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"
//
//可變參數的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 個數的平均數。 arithmeticMean(3, 8.25, 18.75)
// 返回 10.0, 是這 3 個數的平均數。
//
//函數類型作為參數類型:
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:) 來獲得兩個函數其中的一個
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero 現在指向 stepBackward() 函數。
  • 閉包:自包含的函數代碼塊。
    三種形式的閉包:
  • 全局函數是一個有名字但不會捕獲任何值的閉包
  • 嵌套函數是一個有名字并可以捕獲其封閉函數域內值的閉包
  • 閉包表達式是一個利用輕量級語法所寫的可以捕獲其上下文中變量常量值的匿名閉包

閉包表達式:

//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"]
//轉成閉包表達式:
 reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
     return s1 > s2
})
//根據上下文推斷類型
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
//單表達式閉包隱式返回
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )

尾隨閉包:

func someFunctionThatTakesAClosure(closure: () -> Void) { 
// 函數體部分
}
// 以下是不使用尾隨閉包進行函數調用
someFunctionThatTakesAClosure(closure: {
// 閉包主體部分 
})
// 以下是使用尾隨閉包進行函數調用
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
一種自動創建的閉包,用于包裝傳遞給函數作為參數的表達式。不接受任何參數,當它被調用的時候,會返回被包裝在其中的表達式的值。

//延時求值:
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!"
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,936評論 6 535
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,744評論 3 421
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,879評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,181評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,935評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,325評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,384評論 3 443
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,534評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,084評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,892評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,067評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,623評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,322評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,735評論 0 27
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,990評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,800評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,084評論 2 375

推薦閱讀更多精彩內容

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