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

閉包表達(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)
}

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

//延時(shí)求值:
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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容