Get associated value from enumeration without switch/case

前端 未结 2 1050
梦如初夏
梦如初夏 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.

提交回复
热议问题