Accessing an Enumeration association value in Swift

后端 未结 7 778
情深已故
情深已故 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 14:50

    For sake of completeness, enum's association value could be accesed also using if statement with pattern matching. Here is solution for original code:

    enum Number {
      case int (Int)
      case float (Float)
    }
    
    let integer = Number.int(10)
    let float = Number.float(10.5)
    
    if case let .int(i) = integer {
      print("integer is \(i)")
    }
    if case let .float(f) = float {
      print("float is \(f)")
    }
    

    This solution is described in detail in: https://appventure.me/2015/10/17/advanced-practical-enum-examples/

提交回复
热议问题