Accessing an Enumeration association value in Swift

后端 未结 7 775
情深已故
情深已故 2020-11-27 14:46

In this code I\'ve written a really useless enum that defines a possible Number with Int or Float.

I can\'t understand how can I access the value that

7条回答
  •  囚心锁ツ
    2020-11-27 15:06

    It surprises me that Swift 2 (as of beta 2) does not address this. Here's an example of a workaround approach for now:

    enum TestAssociatedValue {
      case One(Int)
      case Two(String)
      case Three(AnyObject)
    
      func associatedValue() -> Any {
        switch self {
        case .One(let value):
          return value
        case .Two(let value):
          return value
        case .Three(let value):
          return value
        }
      }
    }
    
    let one = TestAssociatedValue.One(1)
    let oneValue = one.associatedValue() // 1
    let two = TestAssociatedValue.Two("two")
    let twoValue = two.associatedValue() // two
    
    class ThreeClass {
      let someValue = "Hello world!"
    }
    
    let three = TestMixed.Three(ThreeClass())
    let threeValue = three. associatedValue() as! ThreeClass
    print(threeValue.someValue)
    

    If your enum mixes cases with and without associated values, you'll need to make the return type an optional. You could also return literals for some cases (that do not have associated values), mimicking raw-value typed enums. And you could even return the enum value itself for non-associated, non-raw-type cases. For example:

    enum TestMixed {
      case One(Int)
      case Two(String)
      case Three(AnyObject)
      case Four
      case Five
    
      func value() -> Any? {
        switch self {
        case .One(let value):
          return value
        case .Two(let value):
          return value
        case .Three(let value):
          return value
        case .Four:
          return 4
        case .Five:
          return TestMixed.Five
        }
      }
    }
    
    let one = TestMixed.One(1)
    let oneValue = one.value() // 1
    let two = TestMixed.Two("two")
    let twoValue = two.value() // two
    
    class ThreeClass {
      let someValue = "Hello world!"
    }
    
    let three = TestMixed.Three(ThreeClass())
    let threeValue = three.value() as! ThreeClass
    print(threeValue.someValue)
    
    let four = TestMixed.Four
    let fourValue = four.value() // 4
    
    let five = TestMixed.Five
    let fiveValue = five.value() as! TestMixed
    
    switch fiveValue {
    case TestMixed.Five:
      print("It is")
    default:
      print("It's not")
    }
    // Prints "It is"
    

提交回复
热议问题