Swift:在切换情况下针对可选值进行测试 [英] Swift: testing against optional value in switch case
问题描述
在Swift中,我该如何在switch语句中编写一个case来针对 optional 的内容测试要切换的值,而跳过可选值包含nil
的情况?>
这就是我想象的样子:
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
:
enum Optional<T> : Reflectable, NilLiteralConvertible {
case None
case Some(T)
// ...
}
因此您可以照常匹配它们匹配模式:
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")
}
如果要从 In Swift, how can I write a case in a switch statement that tests the value being switched against the contents of an optional, skipping over the case if the optional contains Here's how I imagine this might look: If I just write it exactly like this, the compiler complains that Optional is just a So you can match them as usual "Associated Values" matching patterns: If you want match from And for Swift > 2.0
这篇关于Swift:在切换情况下针对可选值进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!someValue
中进行匹配,请使用nil
?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
is not unwrapped, but if I explicitly unwrap it by adding !
to the end, I of course get a runtime error any time someOptional
contains nil
. Adding ?
instead of !
would make some sense to me (in the spirit of optional chaining, I suppose), but doesn't make the compiler error go away (i.e. doesn't actually unwrap the optional).enum
like this:enum Optional<T> : Reflectable, NilLiteralConvertible {
case None
case Some(T)
// ...
}
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
, using guard expression:switch someValue {
case let val where val == someOptional:
println(someValue)
default:
break
}
switch someValue {
case let val where val == someOptional:
print("matched")
default:
print("didn't match; default")
}