1、For循环
(1)for in
使用for-in来遍历一个集合里的元素。
for index in ... {
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
上面的例子中,index
是一个每次循环遍历开始时被自动赋值的常量。这种情况下,index
在使用前不需要声明,只需要将它包含在循环的声明中,就可以对其进行隐式声明,而无需使用let
关键字声明。
如果不需要知道区间内每一项的值,你可以使用下划线(_
)替代变量名来忽略对值的访问:
let base =
let power =
var answer =
for _ in ...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// prints "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!
遍历字典:
let numberOfLegs = ["spider": , "ant": , "cat": ]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
// ants have 6 legs
// cats have 4 legs
// spiders have 8 legs
字典元素的遍历顺序和插入顺序可能不同,字典的内容在内部是无序的,所以遍历元素时不能保证顺序。
(2)for(V2.1)
除了for-in
循环,Swift 提供使用条件判断和递增方法的标准 C 样式for
循环:
1 for var index = 0; index < 3; ++index {
2 print("index is \(index)")
3 }
4 // index is 0
5 // index is 1
6 // index is 2
在初始化表达式中声明的常量和变量(比如var index = 0
)只在for
循环的生命周期里有效。如果想在循环结束后访问index
的值,你必须要在循环生命周期开始前声明index
。
1 var index: Int
2 for index = 0; index < 3; ++index {
3 print("index is \(index)")
4 }
5 // index is 0
6 // index is 1
7 // index is 2
8 print("The loop statements were executed \(index) times")
9 // prints "The loop statements were executed 3 times"
2、While循环
(1)while
var square =
var diceRoll =
while square < finalSquare {
// 掷骰子
if ++diceRoll == { diceRoll = }
// 根据点数移动
square += diceRoll
if square < board.count {
// 如果玩家还在棋盘上,顺着*爬上去或者顺着蛇滑下去
square += board[square]
}
}
print("Game over!")
(2)repeat-while
相当于其他语言中的do-while
repeat {
// move up or down for a snake or ladder
square += board[square]
// roll the dice
if ++diceRoll == { diceRoll = }
// move by the rolled amount
square += diceRoll
} while square < finalSquare
print("Game over!")
3、if
temperatureInFahrenheit =
if temperatureInFahrenheit <= {
print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= {
print("It's really warm. Don't forget to wear sunscreen.")
} else {
print("It's not that cold. Wear a t-shirt.")
}
// prints "It's really warm. Don't forget to wear sunscreen."
4、Switch
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")
}
// prints "e is a vowel"
与 C 语言和 Objective-C 中的switch
语句不同,在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch
语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用break
语句。这使得switch
语句更安全、更易用,也避免了因忘记写break
语句而产生的错误。
每一个 case 分支都必须包含至少一条语句。像下面这样书写代码是无效的,因为第一个 case 分支是空的:
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
print("The letter A")
default:
print("Not the letter A")
}
// this will report a compile-time error
一个 case 也可以包含多个模式,用逗号把它们分开(如果太长了也可以分行写):
switch some value to consider {
case value ,
value :
statements
}
(1)区间匹配
let approximateCount =
let countedThings = "moons orbiting Saturn"
var naturalCount: String
switch approximateCount {
case :
naturalCount = "no"
case ..<:
naturalCount = "a few"
case ..<:
naturalCount = "several"
case ..<:
naturalCount = "dozens of"
case ..<:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// prints "There are dozens of moons orbiting Saturn."
(2)元组
let somePoint = (, )
switch somePoint {
case (, ):
print("(0, 0) is at the origin")
case (_, ):
print("(\(somePoint.0), 0) is on the x-axis")
case (, _):
print("(0, \(somePoint.1)) is on the y-axis")
case (-..., -...):
print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
// prints "(1, 1) is inside the box"
(3)值绑定
允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 分支里就可以被引用了。
let anotherPoint = (, )
switch anotherPoint {
case (let x, ):
print("on the x-axis with an x value of \(x)")
case (, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
// prints "on the x-axis with an x value of 2"
(4)Where
Switch的case分支允许用where子句来作额外的判断:
let yetAnotherPoint = (, -)
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")
}
// prints "(1, -1) is on the line x == -y"
(5)复合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")
}
// Prints "e is a vowel"
在复合case语句中也可以使用值绑定:
let stillAnotherPoint = (, )
switch stillAnotherPoint {
case (let distance, ), (, let distance):
print("On an axis, \(distance) from the origin")
default:
print("Not on an axis")
}
// Prints "On an axis, 9 from the origin"
5、控制转移语句
(1)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"
(2)break
当在一个循环体中使用break
时,会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(}
)后的第一行代码。
当在一个switch
代码块中使用break
时,会立即中断该switch
代码块的执行,并且跳转到表示switch
代码块结束的大括号(}
)后的第一行代码。
let numberSymbol: Character = "三" // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "", "١", "一", "๑":
possibleIntegerValue =
case "", "٢", "二", "๒":
possibleIntegerValue =
case "", "٣", "三", "๓":
possibleIntegerValue =
case "", "٤", "四", "๔":
possibleIntegerValue =
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).")
}
// prints "The integer value of 三 is 3."
(3)Fallthrough
Swift 中的switch
不会从上一个 case 分支落入到下一个 case 分支中。相反,只要第一个匹配到的 case 分支完成了它需要执行的语句,整个switch
代码块完成了它的执行。相比之下,C 语言要求你显示的插入break
语句到每个switch
分支的末尾来阻止自动落入到下一个 case 分支中。
如果需要 C 风格的贯穿的特性,可以在每个需要该特性的 case 分支中使用fallthrough
关键字:
let integerToDescribe =
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case , , , , , , , :
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
print(description)
// prints "The number 5 is a prime number, and also an integer."
注意: fallthrough
关键字不会检查它下一个将会落入执行的 case 中的匹配条件。fallthrough
简单地使代码执行继续连接到下一个 case 中的执行代码,这和 C 语言标准中的switch
语句特性是一样的。
(4)带Label的语句
在 Swift 中,可以在循环体和switch
代码块中嵌套循环体和switch
代码块来创造复杂的控制流结构。然而,循环体和switch
代码块两者都可以使用break
语句来提前结束整个方法体。因此,显示地指明break
语句想要终止的是哪个循环体或者switch
代码块,会很有用。类似地,如果你有许多嵌套的循环体,显示指明continue
语句想要影响哪一个循环体也会非常有用。
为了实现这个目的,你可以使用标签来标记一个循环体或者switch
代码块,当使用break
或者continue
时,带上这个标签,可以控制该标签代表对象的中断或者执行。
gameLoop: while square != finalSquare {
if ++diceRoll == { diceRoll = }
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(["name": "John"])
// prints "Hello John!"
// prints "I hope the weather is nice near you."
greet(["name": "Jane", "location": "Cupertino"])
// prints "Hello Jane!"
// prints "I hope the weather is nice in Cupertino."
如果条件不被满足,在else
分支上的代码就会被执行。这个分支必须转移控制以退出guard
语句出现的代码段。它可以用控制转移语句如return
,break
或continue
做这件事,或者调用一个不返回的方法或函数,例如fatalError()
。
与可以实现同样功能的if
语句相比,使用guard
语句会提升我们代码的可靠性。 可以使你的代码连贯地被执行而不需要将它包在else
块中,它可以使你处理违反要求的代码接近要求。
(6)检查API的可用性
if #available(iOS , OSX 10.10, *) {
// Use iOS 9 APIs on iOS, and use OS X v10.10 APIs on OS X
} else {
// Fall back to earlier iOS and OS X APIs
}
以上可用性条件指定在iOS平台下,if
段的代码仅仅在iOS9及更高系统中可运行;在OS X平台下,仅在OS X v10.10及更高系统可运行。最后一个参数,*
,是必须的并且指定在任何其他平台上,if
段的代码在最小可用部署目标指定项目中执行。
在它普遍的形式中,可用性条件获取了平台名字和版本的清单。平台名字可以是iOS
,OSX
或watchOS
。除了特定的主板本号像iOS8,我们可以指定较小的版本号像iOS8.3以及 OS X v10.10.3。
if #available(platform name version, ..., *) {
statements to execute if the APIs are available
} else {
fallback statements to execute if the APIs are unavailable
}