1、For-in 循环
可以使用 for-in
循环来遍历一个集合中的所有元素,例如数组中的元素、范围内的数字或者字符串中的字符。
- 使用
for-in
遍历一个数组所有元素:
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
- 使用
for-in
遍历字典
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
// cats have 4 legs
// ants have 6 legs
// spiders have 8 legs
- 使用
for-in
遍历数字范围
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
- 如果不需要区间序列内每一项的值,可以使用下划线(
_
)替代变量名来忽略这个值
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// 输出“3 to the power of 10 is 59049”
- 半开区间使用
stride(from:to:by:)
函数跳过不需要的标记。
let minutes = 60
for tickMark in 0..<minutes {
// 每一分钟都渲染一个刻度线(60次)
}
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
// 每5分钟渲染一个刻度线(0, 5, 10, 15 ... 45, 50, 55)
}
- 在闭区间使用
stride(from:through:by:)
函数跳过不需要的标记
let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
// 每3小时渲染一个刻度线(3, 6, 9, 12)
}
2、While 循环
while
循环会一直运行一段语句直到条件变成 false
。这类循环适合使用在第一次迭代前,迭代次数未知的情况下。Swift 提供两种 while
循环形式:
-
while
循环,每次在循环开始时计算条件是否符合; -
repeat-while
循环,每次在循环结束时计算条件是否符合。
(1)While
while
循环从计算一个条件开始。如果条件为true
,会重复运行一段语句,直到条件变为 false
。while
循环的一般格式:
while condition {
statements
}
蛇和梯子的小游戏:

规则如下:
- 游戏盘面包括 25 个方格,游戏目标是达到或者超过第 25 个方格;
- 每一轮,你通过掷一个六面体骰子来确定你移动方块的步数,移动的路线由上图中横向的虚线所示;
- 如果在某轮结束,你移动到了梯子的底部,可以顺着梯子爬上去;
- 如果在某轮结束,你移动到了蛇的头部,你会顺着蛇的身体滑下去。
let finalSquare = 25
var board = [Int](repeating: 0, count: finalSquare + 1)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
while square < finalSquare {
// 掷骰子
diceRoll += 1
if diceRoll == 7 { diceRoll = 1 }
// 根据点数移动
square += diceRoll
if square < board.count {
// 如果玩家还在棋盘上,顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
}
}
print("Game over!")
(2)Repeat-While
while
循环的另外一种形式是 repeat-while
,它和 while
的区别是在判断循环条件之前,先执行一次循环的代码块。然后重复循环直到条件为 false
。
下面是 repeat-while
循环的一般格式:
repeat {
statements
} while condition
蛇和梯子小游戏用 repeat-while
实现如下:
let finalSquare = 25
var board = [Int](repeating: 0, count: finalSquare + 1)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
repeat {
// 顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
// 掷骰子
diceRoll += 1
if diceRoll == 7 { diceRoll = 1 }
// 根据点数移动
square += diceRoll
} while square < finalSquare
print("Game over!")
3、条件语句
(1)If
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
print("It's really warm. Don't forget to wear sunscreen.")
} else {
print("It's not that cold. Wear a t-shirt.")
}
// 输出“It's really warm. Don't forget to wear sunscreen.”
2、Switch
switch
语句最简单的形式就是把某个值与一个或若干个相同类型的值作比较
switch some value to consider {
case value 1:
respond to value 1
case value 2,
value 3:
respond to value 2 or 3
default:
otherwise, do something else
}
- 不存在隐式的贯穿
在 Swift 中,当匹配的case
分支中的代码执行完毕后,程序会终止switch
语句,而不会继续执行下一个case
分支 - 每一个
case
分支都必须包含至少一条语句,否则代码无效
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // 无效,这个分支下面没有语句
case "A":
print("The letter A")
default:
print("Not the letter A")
}
// 这段代码会报编译错误
-
case
分支的模式也可以是一个值的区间
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let 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.”
- 可以使用元组在同一个
switch
语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划线(_
)来匹配所有可能的值。
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("\(somePoint) is at the origin")
case (_, 0):
print("\(somePoint) is on the x-axis")
case (0, _):
print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
print("\(somePoint) is inside the box")
default:
print("\(somePoint) is outside of the box")
}
// 输出“(1, 1) is inside the box”
-
值绑定
:case
分支允许将匹配的值声明为临时常量或变量,并且在case
分支体内使用
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”
-
case
分支的模式可以使用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”
-
复合型 Cases
当多个条件可以使用同一种方法来处理时,可以将这几种可能放在同一个case
后面,并且用逗号隔开,并且,如果匹配列表过长,还可以分行书写:
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("\(someCharacter) is a consonant")
default:
print("\(someCharacter) is not a vowel or a consonant")
}
// 输出“e is a vowel”
4、控制转移语句
控制转移语句改变代码的执行顺序,通过它可以实现代码的跳转。Swift 有五种控制转移语句:
continue
break
fallthrough
return
throw
(1)Continue
continue
语句:停止本次循环,开始下次循环,不是停止整个循环体
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default:
puzzleOutput.append(character)
}
}
print(puzzleOutput)
// 输出“grtmndsthnklk”
(2)Break
- 循环语句中的
break
会立刻中断该循环体的执行 -
Switch
语句中的break
当在一个switch
代码块中使用break
时,会立即中断该switch
代码块的执行。break
也可以被用来忽略一个或多个分支。
let numberSymbol: Character = "三" // 简体中文里的数字 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
possibleIntegerValue = 1
case "2", "٢", "二", "๒":
possibleIntegerValue = 2
case "3", "٣", "三", "๓":
possibleIntegerValue = 3
case "4", "٤", "四", "๔":
possibleIntegerValue = 4
default:
break
}
if let integerValue = possibleIntegerValue {
print("The integer value of \(numberSymbol) is \(integerValue).")
} else {
print("An integer value could not be found for \(numberSymbol).")
}
// 输出“The integer value of 三 is 3.”
(3)贯穿(fallthrough
)
fallthrough
使得 Switch
语句执行完上一个 case
分支之后,继续执行下一个 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.”
(4)带标签的语句
使用标签
(statement label)来标记一个循环体或者条件语句,对于一个条件语句,你可以使用 break
加标签的方式,来结束这个被标记的语句。对于一个循环语句,你可以使用 break
或者 continue
加标签,来结束或者继续这条被标记语句的执行。
label name: while condition {
statements
}
蛇和梯子小游戏:
let finalSquare = 25
var board = [Int](repeating: 0, count: finalSquare + 1)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
//必须刚好落在第 25 个方块中
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!")
5、提前退出
像 if
语句一样,guard
的执行取决于一个表达式的布尔值。我们可以使用 guard
语句来要求条件必须为真时,以执行 guard
语句后的代码。不同于if
语句,一个 guard
语句总是有一个 else
从句,如果条件不为真则执行 else
从句中的代码
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)!")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in \(location).")
}
greet(person: ["name": "John"])
// 输出“Hello John!”
// 输出“I hope the weather is nice near you.”
greet(person: ["name": "Jane", "location": "Cupertino"])
// 输出“Hello Jane!”
// 输出“I hope the weather is nice in Cupertino.”
6、检测API可用性
if #available(平台名称 版本号, ..., *) {
APIs 可用,语句将执行
} else {
APIs 不可用,语句将不执行
}
网友评论