Swift 2.0: Catching enums having associated values

Many blogs touch on the ability of Swift to throw an enumeration that contains a payload value, but no one has really shown how to get the associated values – particularly if the different enumeration payloads differ in type.

Here is an example, which shows how to catch those errors and extract the associated value:

enum Foo : ErrorType {
case First(String)
case Second(Int)
}

func flup(i: Int) throws -> Bool {
  if i == 0 {
    throw Foo.First("Howdie")
  }
  if i == 1 {
    throw Foo.Second(2)
  }
  if i == 2 {
    throw Foo.Second(4)
  }
  return true
}

print("Howdie")

do {
  try flup(0)
} catch Foo.First(let error) {
  print("ERROR: \(error)")
} catch {
  print("WTF: \(error)")
}

do {
  try flup(1)
} catch Foo.First(let error) {
  print("ERROR 1: \(error)")
} catch Foo.Second(let error) {
  print("ERROR 2: \(error)")
} catch {
  print("WTF: \(error)")
}

do {
try flup(2)
} catch Foo.First(let error) {
  print("ERROR 1: \(error)")
} catch Foo.Second(let error) {
  print("ERROR 2: \(error)")
} catch {
  print("WTF: \(error)")
}

This is what appears on the console:

Howdie
ERROR: Howdie
ERROR 2: 2
ERROR 2: 4

Leave a comment