Swift:在switch case中测试可选值

问题描述 投票:76回答:3

在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的任何时候得到运行时错误。添加?而不是!会对我有所帮助(我认为可选链接的精神),但不会使编译器错误消失(即实际上不打开可选的)。

swift enums switch-statement optional
3个回答
103
投票

可选的只是像这样的enum

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")        
}

44
投票

从Xcode 7开始(来自beta 1发行说明),“一个新的x?模式可用于模式匹配选项作为.Some(x)的同义词。”这意味着在Xcode 7及更高版本中,rintaro's answer的以下变体也将起作用:

switch someOptional {
case someValue?:
    print("the value is \(someValue)")
case let val?:
    print("the value is \(val)")
default:
    print("nil")
}

4
投票

在Swift 4中,您可以使用可选:Apple的ExpressibleByNilLiteral来包装可选

https://developer.apple.com/documentation/swift/optional

enum MyEnum {
    case normal
    case cool
}

一些

let myOptional: MyEnum? = MyEnum.normal

switch smyOptional {
    case .some(.normal): 
    // Found .normal enum
    break

    case .none: 
    break

    default:
    break
}

没有

let myOptional: MyEnum? = nil

switch smyOptional {
    case .some(.normal): 
    break

    case .none: 
    // Found nil
    break

    default:
    break
}

默认

let myOptional: MyEnum? = MyEnum.cool

switch smyOptional {
    case .some(.normal): 
    break

    case .none: 
    break

    default:
    // Found .Cool enum
    break
}

有价值的枚举

enum MyEnum {
    case normal(myValue: String)
    case cool
}

一些价值

let myOptional: MyEnum? = MyEnum.normal("BlaBla")

switch smyOptional {
case .some(.normal(let myValue)) where myValue == "BlaBla":
    // Here because where find in my myValue "BlaBla"
    break

// Example for get value
case .some(.normal(let myValue)):
    break

// Example for just know if is normal case enum
case .some(.normal):
    break

case .none:
    break

default:

    break
}
© www.soinside.com 2019 - 2024. All rights reserved.