Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2016-01-30

Swift Design Pattern: Switch with 'when ... is' clauses

I like the enums in Swift, and I like the switch statement.

However, they not always work perfectly together. Take the following case:

enum Test {
    case First(data: Any)
    case Second
}

let t = Test.First(data: 3)

switch t {
case let .First(number) where number is Int: print("First(\(number)")
case .Second: print("Second")

}

In this case we get the error message:

error: switch must be exhaustive, consider adding a default clause

Which can be easily done as follows:

switch t {
case let .First(number) where number is Int: print("First(\(number)")
case .Second: print("Second")
default: print("Oeps")

}

But that does not sit right with me. I like a warning when I update an enum and forget to update an associated switch statement. Or as in de above case, suddenly start using the Test enum as .First(1.0) Using a default clause makes that impossible.

Unless... well the solution is obvious:

switch t {
case let .First(number) where number is Int: print("First(\(number)")
case .Second: print("Second")
default:
    switch t {
    case .First: print("Forgot to add a case with when..is clause")
    default: break
    }

}

A 'staggered' switch. It does not look all that nice, but it will catch any errors I might make. Either when adding new Enum cases, or when using the existing case with the wrong type for associated parameter.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment