letsomeCharacter:Character="e"switchsomeCharacter{case"a","e","i","o","u":println("\(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":println("\(someCharacter) is a consonant")default:println("\(someCharacter) is not a vowel or a consonant")}// 输出 "e is a vowe
1.2.1不存在隐式的贯穿
与 C 语言和 Objective-C 中的switch语句不同,在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用break语句。
letcount=3_000_000_000_000letcountedThings="stars in the Milky Way"varnaturalCount: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).")// 输出 "There are millions and millions of stars in the Milky Way."
letsomePoint=(1,1)switchsomePoint{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")}// 输出 "(1, 1) is inside the box"
letanotherPoint=(2,0)switchanotherPoint{case(letx,0):println("on the x-axis with an x value of \(x)")case(0,lety):println("on the y-axis with a y value of \(y)")caselet(x,y):println("somewhere else at (\(x), \(y))")}// 输出 "on the x-axis with an x value of 2"
letyetAnotherPoint=(1,-1)switchyetAnotherPoint{caselet(x,y)wherex==y:println("(\(x), \(y)) is on the line x == y")caselet(x,y)wherex==-y:println("(\(x), \(y)) is on the line x == -y")caselet(x,y):println("(\(x), \(y)) is just some arbitrary point")}// 输出 "(1, -1) is on the line x == -y"
letbase=3letpower=10varanswer=1for_in1...power{answer*=base}println("\(base) to the power of \(power) is \(answer)")// 输出 "3 to the power of 10 is 59049"
letintegerToDescribe=5vardescription="The number \(integerToDescribe) is"switchintegerToDescribe{case2,3,5,7,11,13,17,19:description+=" a prime number, and also"fallthroughdefault:description+=" an integer."}println(description)// 输出 "The number 5 is a prime number, and also an integer."