Get associated value from enumeration without switch/case

前端 未结 2 1041
梦如初夏
梦如初夏 2020-11-29 09:55

I\'ve got an enumeration with a few different cases which are different types, e.g.

enum X {
    case AsInt(Int)
    case AsDouble(Double)
}
<
相关标签:
2条回答
  • 2020-11-29 10:16

    As of Swift 2 (Xcode 7) this is possible with if/case and pattern matching:

    let x : X = ...
    if case let .AsInt(num) = x {
        print(num)
    }
    

    The scope of num is restricted to the if-statement.

    0 讨论(0)
  • 2020-11-29 10:25

    There are actually multiple ways to do it.

    Let's do it by extending your enum with a computed property:

    enum X {
        case asInt(Int)
        case asDouble(Double)
    
        var asInt: Int? {
            // ... see below
        }
    }
    

    Solutions with if case

    By having let outside:

    var asInt: Int? {
        if case let .asInt(value) = self {
            return value
        }
        return nil
    }
    

    By having let inside:

    var asInt: Int? {
        if case .asInt(let value) = self {
            return value
        }
        return nil
    }
    

    Solutions with guard case

    By having let outside:

    var asInt: Int? {
        guard case let .asInt(value) = self else {
            return nil
        }
        return value
    }
    

    By having let inside:

    var asInt: Int? {
        guard case .asInt(let value) = self else {
            return nil
        }
        return value
    }
    

    The last one is my personal favorite syntax of the four solutions.

    0 讨论(0)
提交回复
热议问题