與Objective-C中這部分內(nèi)容相比,在Swift中switch得到了極大的改善。這是一件非常有趣的事,因?yàn)檫@還是沒有添加到Objective-C中,還是沒有打破Objective-C是C的超集的事實(shí)。
第一件令人興奮的地方是可以對字符串轉(zhuǎn)換。這也許正是你之前想要做,卻不能做的事。在Objective-C中如果要對字符串用“switch”,你必須要使用多個(gè)if語句,同時(shí)要用isEqualToString:,像下面這樣:
if ([person.name isEqualToString:@"Matt Galloway"]) { NSLog(@"Author of an interesting Swift article");} else if ([person.name isEqualToString:@"Ray Wenderlich"]) { NSLog(@"Has a great website");} else if ([person.name isEqualToString:@"Tim Cook"]) { NSLog(@"CEO of Apple Inc.");} else { NSLog(@"Someone else);} 這樣可閱讀性不強(qiáng),也要打很多字。同樣的功能在Swift中實(shí)現(xiàn)如下:
switch person.name { case "Matt Galloway": println("Author of an interesting Swift article") case "Ray Wenderlich": println("Has a great website") case "Tim Cook": println("CEO of Apple Inc.") default: println("Someone else")} 除了對字符串可以使用switch之外,請注意這里一些有趣的事情。沒有看見break。因?yàn)樵趕witch中一個(gè)case語句執(zhí)行完成后就不再向下執(zhí)行。不會(huì)再偶然地出現(xiàn)bug!
再比如這樣的情況下
let vegetable = "red pepper"switch vegetable{ case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber","watercress": let vegetableComment = "That would make a good tea sandwich." //switch支持所有類型的數(shù)據(jù),以及多種比較運(yùn)算——沒有限制為必須是整數(shù),也沒有限制為必須測試相等(tests for equality 真的是這樣翻譯的嗎?) case let x where x.hasSuffix("pepper"): let vagetableComment = "Is it a spicy /(x)?" //switch語句要求必須覆蓋所有的可能,否則報(bào)錯(cuò)'switch must be exhaustive, consider adding a default cla' default: print("不能沒有default")} 不需要寫break,
執(zhí)行完匹配到的case后,程序會(huì)跳出switch,而不是繼續(xù)執(zhí)行下一個(gè)case,所以不需要在case的代碼后面添加break來跳出switch。
下面的switch語句可能會(huì)擾亂你的思路,所以準(zhǔn)備好了!
switch i {case 0, 1, 2: println("Small")case 3...7: println("Medium")case 8..10: println("Large")case _ where i % 2 == 0: println("Even")case _ where i % 2 == 1: println("Odd")default: break} 首先,這出現(xiàn)了一個(gè)break。因?yàn)閟witch必須要全面而徹底,它們需要處理所有的情況。在這種情況下,我們想要default時(shí)不做任何事,所以放置了一個(gè)break來表明此處不應(yīng)該發(fā)生任何事。
接下來有趣的事情是你在上面看到的…和..,這些是新的操作符,用于來定義范圍。前者用來定義范圍包括右邊的數(shù)字,后者定義的范圍不包括右邊的數(shù)字。它們真是超乎想象地有用。
最后一件事是可以把case定義成對輸入值的計(jì)算。在上面這種情況下,如果這個(gè)值不匹配從0到10,如果是偶數(shù)打印“Even”,是奇數(shù)打印“Odd”。太神奇了!



















