在代码业务中,条件判断是必不可少的,控制流程的语句在每种语言中都是差不多的。swift包括了:
if,switch,for-in,for,while,do-while
if 条件语句 (if else) (if... else if ... else)
判断条件为true时执行相关代码。例如:
var a = 0
if a > 0 {
println("a > 0")
}else if a == 0{
println("a = 0")
}else{
println("a < 0")
}
switch switch语句会尝试把某个值与若干个模式(pattern)进行匹配。根据第一个匹配成功的模式,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")
}
switch有几个注意事项:
1、case语句下必须包含至少一行代码
2、case语句下可以不包含break,它不存在隐式的贯穿
3、case可以进行区间匹配
Let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
naturalCount = "no"
case 1...3:
naturalCount = "a few"
case 4...9:
naturalCount = "several"
case 10...99:
naturalCount = "tens of"
case 100...999:
naturalCount = "hundreds of"
case 1000...999_999:
naturalCount = "thousands of"
default:
naturalCount = "millions and millions of"
}
print("There are \(naturalCount) \(countedThings).")
例如:
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")
}
5、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")
}