Switch作为选择结构中必不可少的语句也被加入到了Swift中,只要有过编程经验的人对Switch语句都不会感到陌生,但苹果对Switch进行了大大的增强,使其拥有其他语言中没有的特性。使用Switch语句很简单:
var i = 0 switch i { case 0: "0" //被输出 case 1: "1" default: "2" }
var i = 3 switch i { case 0,3: "0" //被输出 case 1: "1" default: "2" }
如果就是想执行完一条case之后,想继续执行下一条case,就要用到一个新的关键字:
var i = 0 switch i { case 0: "0" //被输出 fallthrough case 1: "1" //被输出 case 2: "2" default: "default" }
使用新的关键字fallthrough能使Switch在执行完一个case之后,紧接着执行下一条case。
Swift的Switch语句一定要涵盖所有的情况,这并不是说一定要有default,只要上面的case能满足所有的情况,就可以不用写default。
需要注意的地方有两点:
let float = 1.5 switch float { case 1.5: "1.5" //被输出 default: "default" }
let isSuccess = true switch isSuccess { case true: "true" //被输出 default: "default" }
let name = "Bannings" switch name { case "Bannings": "Bannings" //被输出 default: "default" }
var i = 15 switch i { case 0 ... 10: "0~10" case 11 ... 20: "11~20" //被输出 default: "default" }
let request = (true,"success") switch request { case (true, "success"): "success" //被输出 case (false, "failed"): "failed" default: "default" }
let (name, _, age) = ("Bannings" ,true, 22)
let request = (10,"failed") switch request { case (_, "success"): "success" case (1 ... 10, _): "1~10" //被输出 default: "default" }
let request = (0,"success") switch request { case (0, let state): state //被输出:success case (let errorCode, _): "error code is \(errorCode)" } // 涵盖了所有可能的case,不用写default了
let request = (0,"success") switch request { case let (errorCode, state): state //被输出:success case (let errorCode, _): "error code is \(errorCode)" }
只要把下面的errorCode去掉就行了,当然,考虑好自己的逻辑。
let request = (0,"success") switch request { case (0, let state) where state != "success": state case (let errorCode, _): "error code is \(errorCode)"//被输出:"error code is 0" }