let count=3_000_000_000_000
let countedThings ="stars in the Milky Way"var naturalCount:Stringswitchcount{case0:
naturalCount ="no"case1...3:
naturalCount ="a few"case4...9:
naturalCount ="several"case10...99:
naturalCount ="tens of"case100...999:
naturalCount ="hundreds of"case1000...999_999:
naturalCount ="thousands of"default:
naturalCount ="millions and millions of"}
println("There are \(naturalCount) \(countedThings).")// prints "There are millions and millions of stars in the Milky Way."
元组
case中还可以直接测试元组是否符合相应的条件,_可以匹配任意值。
下面的例子是判断(x,y)是否在矩形中,元组类型是(Int,Int)
1234567891011121314
let somePoint =(1,1)switch somePoint {case(0,0):
println("(0, 0) is at the origin")case(_,0):
println("(\(somePoint.0), 0) is on the x-axis")case(0, _):
println("(0, \(somePoint.1)) is on the y-axis")case(-2...2,-2...2):
println("(\(somePoint.0), \(somePoint.1)) is inside the box")default:
println("(\(somePoint.0), \(somePoint.1)) is outside of the box")}// prints "(1, 1) is inside the box"
let anotherPoint =(2,0)switch anotherPoint {case(let x,0):
println("on the x-axis with an x value of \(x)")case(0, let y):
println("on the y-axis with a y value of \(y)")case let (x, y):
println("somewhere else at (\(x), \(y))")}// prints "on the x-axis with an x value of 2"
Where关键词
switch语句可以使用where关键词来增加判断的条件,在下面的例子中:
12345678910
let yetAnotherPoint =(1,-1)switch yetAnotherPoint {case let (x, y)where x == y:
println("(\(x), \(y)) is on the line x == y")case let (x, y)where x ==-y:
println("(\(x), \(y)) is on the line x == -y")case let (x, y):
println("(\(x), \(y)) is just some arbitrary point")}// prints "(1, -1) is on the line x == -y"
let integerToDescribe =5var description ="The number \(integerToDescribe) is"switch integerToDescribe {case2,3,5,7,11,13,17,19:
description +=" a prime number, and also"
fallthrough
default:
description +=" an integer."}
println(description)// prints "The number 5 is a prime number, and also an integer."