ios - 在 Swift 中对元组进行模式匹配时如何解包 Optional?

标签 ios swift pattern-matching option-type

在 Swift 中,有一个常见的 if let 模式用于解包可选值:

if let value = optional {
    print("value is now unwrapped: \(value)")
}

我目前正在做这种模式匹配,但是在 switch case 中使用元组,其中两个参数都是可选的:

//url is optional here
switch (year, url) {
    case (1990...2015, let unwrappedUrl):
        print("Current year is \(year), go to: \(unwrappedUrl)")
}       

然而,这打印:

"Current year is 2000, go to Optional(www.google.com)"

有没有一种方法可以解包我的可选和模式匹配,只有当它不是零时?目前我的解决方法是:

switch (year, url) {
    case (1990...2015, let unwrappedUrl) where unwrappedUrl != nil:
        print("Current year is \(year), go to: \(unwrappedUrl!)")
}       

最佳答案

您可以使用 x? 模式:

case (1990...2015, let unwrappedUrl?):
    print("Current year is \(year), go to: \(unwrappedUrl)")

x? 只是 .some(x) 的快捷方式,所以这等同于

case (1990...2015, let .some(unwrappedUrl)):
    print("Current year is \(year), go to: \(unwrappedUrl)")

关于ios - 在 Swift 中对元组进行模式匹配时如何解包 Optional?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37452118/

相关文章:

ios - SCNText 不显示

iphone - 在不改变顺序的情况下将 nsdictionary 的内容放入 nsarray

ios - textField :shouldChangeCharactersInRange method? 内的多个语句

javascript - Javascript 模式中的语法错误

ios - 在 SceneKit 中跨球体绘制文本

ios - 使用 TestFlight 的 iOS 应用程序大小意外增加

generics - 如何为嵌套在泛型结构中的类实现运算符?

swift - 从枚举数组中删除枚举,无论其参数如何

F#/OCaml : How to avoid duplicate pattern match?

makefile - GNU Make——模式匹配的依赖关系