在Swift中,如何在switch语句中编写一个case来测试根据可选内容切换的值,如果可选项包含nil则跳过case?
以下是我的想象:
let someValue = 5 let someOptional: Int? = nil switch someValue { case someOptional: // someOptional is non-nil,and someValue equals the unwrapped contents of someOptional default: // either,someOptional is nil,or someOptional is non-nil but someValue does not equal the unwrapped contents of someOptional }
如果我只是这样编写它,编译器会抱怨someOptional没有解包,但如果我通过添加显式解包它!到最后,我当然会在someOptional包含nil的任何时候得到运行时错误.添加?代替 !会对我有所帮助(我认为可选链接的精神),但不会使编译器错误消失(即实际上不打开可选的).
可选只是这样的枚举:
enum Optional<T> : Reflectable,NilLiteralConvertible { case None case Some(T) // ... }
所以你可以照常匹配它们“Associated Values”匹配模式:
let someValue = 5 let someOptional: Int? = nil switch someOptional { case .Some(someValue): println("the value is \(someValue)") case .Some(let val): println("the value is \(val)") default: println("nil") }
如果你想从someValue匹配,使用guard expression:
switch someValue { case let val where val == someOptional: println(someValue) default: break }
而对于Swift> 2.0
switch someValue { case let val where val == someOptional: print("matched") default: print("didn't match; default") }