首页 > 解决方案 > 如何在 Swift 的 switch 语句中捕获选项的值?

问题描述

我有一个函数,我将 a 解析String为 a BoolDouble或者Int在回退到 a 之前String。目前我使用这样的 if-else 条件

func parse(stringValue: String) {

    if let value = Bool(stringValue) {
        // do something with a Bool
        print(value)

    } else if let value =  Int(stringValue)  {
        // do something with a Int
        print("\(stringValue) is Int: \(value)")
    } else if let value = Double(stringValue) {
        // do something with a Double
        print("\(stringValue) is Double: \(value)")
    } else {
        // do something with a String
        print("String: \(stringValue)")
    }
}

这没关系,但我个人的偏好是在 Swift 中使用 switch 语句,但我不知道如何在不强制展开的情况下这样做:

func parse(stringValue: String) {

    switch stringValue {
    case _  where Bool(stringValue) != nil:
        let value = Bool(stringValue)!
        // do something with Bool
    case _ where Int(stringValue) != nil:
        let value = Int(stringValue)!
        // do something with Int
    case _ where Double(stringValue) != nil:
        let value = Double(stringValue)!
        // do something with Double
    default:
        // do something with String
    }
}

如何捕获结果where以便我可以在case范围内使用它?

标签: swiftswitch-statement

解决方案


推荐阅读