- 控制流: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!"