Accessing an Enumeration association value in Swift

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/

Leave a Comment