中针对可选值进行测试

中针对可选值进行测试

本文介绍了Swift:在 switch case 中针对可选值进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,如何在 switch 语句中编写一个 case 来测试根据 optional 的内容切换的值,如果可选包含 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 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 时,当然会出现运行时错误.添加 ? 而不是 ! 对我来说有些意义(我想是本着可选链接的精神),但不会使编译器错误消失(即并没有真正解开可选的).

If I just write it exactly like this, the compiler complains that 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).

推荐答案

Optional 只是一个 enum 像这样:

Optional is just a enum like this:

enum Optional<T> : Reflectable, NilLiteralConvertible {
    case none
    case some(T)

    // ...
}

所以你可以像往常一样匹配它们关联值" 匹配模式:

So you can match them as usual "Associated Values" matching patterns:

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 匹配,使用 保护表达式:

If you want match from someValue, using 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")
}

这篇关于Swift:在 switch case 中针对可选值进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:23