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
let anotherCharacter: Character = "a"switch anotherCharacter {
case"a":
case"A":
print("The letter A")
default:
print("Not the letter A")
}
//这么写,在OC里对,在Swift里报错
let anotherCharacter: Character = "a"switch anotherCharacter {
case"a":
fallthroughcase"A":
print("The letter A")
default:
print("Not the letter A")
}
//好吧,加上贯穿关键字:fallthrough,输出:The letter A
Switch的区间匹配
let count = 30let countedThings = "stars in the Milky Way"var naturalCount: Stringswitch count {
case0:
naturalCount = "no"case1...9:
naturalCount = "a few"case10...99:
naturalCount = "tens of"case100...999:
naturalCount = "hundreds of"default:
naturalCount = "thousands and millions of"
}
print("There are \(naturalCount) \(countedThings).")
//输出:There are tens of stars in the Milky Way.
Switch与元组
元组中下划线(_)可以用来匹配所有可能的值
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)")
caselet (x, y):
print("somewhere else at (\(x), \(y))")
}
//输出:on the x-axis with an x value of2