1. For-in 循环
使用 for...in
循环来遍历序列:
for index in 1...5 { // index 是一个常量,它的值隐式地在循环中声明了,不需要再用let声明。
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"
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")
}
// ants have 6 legs
// cats have 4 legs
// spiders have 8 legs
2. While 循环
While 语句
while
循环的通用格式:
while condition {
statements
}
// while 循环通过判断condition开始,如果 condition 为 true,大括号语句就重复执行到 condition 为 false。
如:
var index = 0
while index < 3 {
print "index: \(index)"
index += 1
}
// index: 0
// index: 1
// index: 2
Repeat-While 语句
Repeat-While 循环的通用格式:
repeat {
statements
} while condition
// repeat-while 在判断 condition 之前已执行一次代码块。然后继续循环直到条件为 false 。
如:
var index = 0
repeat {
print "index: \(index)"
index += 1
}while index < 3
// index: 0
// index: 1
// index: 2
3. 条件语句
If 语句
最简单的形式:
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}
// 结果为: "It's very cold. Consider wearing a scarf."
带else
分句的if
语句:
temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else {
print("It's not that cold. Wear a t-shirt.")
}
// 结果为: "It's not that cold. Wear a t-shirt."
带多个分支的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 { // 此 else 语句可以省略
print("It's not that cold. Wear a t-shirt.")
}
// 结果为: "It's really warm. Don't forget to wear sunscreen."
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
}
注意: 任何case对应的语句不能为空;符合某个case并执行完成此case对应的语句后,立即跳出
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 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): // 将匹配的值绑定给常量 x
print("on the x-axis with an x value of \(x)")
case (0, let y): // 将匹配的值绑定给常量 y
print("on the y-axis with a y value of \(y)")
case let (x, y): // 将匹配的值绑定给常量 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: // x == y 的情况
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y: // 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"
多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
Continue 语句
continue
语句告诉循环停止接下来要做的事情,并开始下一轮循环,举个例子:
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
switch character {
case "a", "e", "i", "o", "u", " ": // 遇到这些字符时,直接执行下一轮循环
continue
default:
puzzleOutput.append(character)
}
}
print(puzzleOutput)
// 结果为: "grtmndsthnklk"
Break 语句
Break
立即跳出整体Switch或循环代码块:
let numberSymbol: Character = "三" // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
possibleIntegerValue = 1
case "2", "٢", "二", "๒":
possibleIntegerValue = 2
case "3", "٣", "三", "๓":
possibleIntegerValue = 3
case "4", "٤", "四", "๔":
possibleIntegerValue = 4
default:
break // 默认情况下,立即跳出Swich语句
}
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."
Fallthrough 语句
Switch
语句,默认符合某个case时跳出,不再匹配随后的case。但如果需要贯穿行为,可以在每个case末尾使用fallthrough
关键字:
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 // fallthrough后,代码紧接着执行default中的语句。
default:
description += " an integer."
}
print(description)
// 结果为: "The number 5 is a prime number, and also an integer."
给语句打标签
由于循环和条件语句可以相互内嵌,显式标明break
或者coontinue
具体哪个循环或者条件语句很有必要,因此可以为这个语句打个标签,通用格式为:
标签名字: 循环或Switch语句 {
statements
}
举个栗子:
let finalSquare = 25
var square = 0
var diceRoll = 0
gameLoop: while square != finalSquare { // 此处,为循环语句打了个gameLoop标签
diceRoll += 1
if diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare:
break gameLoop // 如果不写gameLoop,跳出的是Switch语句而不是循环
case let newSquare where newSquare > finalSquare:
continue gameLoop // 写不写gameLoop,没有区别
default:
square += diceRoll
square += board[square]
}
}
print("Game over!")
guard...else 语句
guard
语句要求条件为真才能执行guard
语句后的代码,否则只执行else
中的语句:
注意: 1.
else
分支要用return
,break
,continue
,throw
或者一个无返回值的函数如fatalError()
结尾。 2.guard
条件中,使用可选项绑定而被赋值的变量或者常量,在整个guard代码块结束后中都是可用的。
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)!") // name 常量在guard代码块结束后仍然可以访问
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(["name": "John"])
// 结果为: "Hello John!"
// 结果为: "I hope the weather is nice near you."
greet(["name": "Jane", "location": "Cupertino"])
// 结果为: "Hello Jane!"
// 结果为: "I hope the weather is nice in Cupertino."
#available 语句
对API可用性进行检查,如:
if #available(iOS 10, macOS 10.12, *) {
// iOS平台使用iOS 10的API, macOS平台使用macOS 10.12的API。
} else {
// 使用更早版本的API
}