Swift icon Swift

Swift 5 @unknown attribute

Swift 5 is already in beta and contains some very nice features! In this post I want to dive a little bit deeper in the new @unknown attribute for enums.

Enums are great in Swift! You can specify your intentions more clearly and make your code more readable, who does not want that? Writing a switch statement is easy enough, though it can be a hassle if you have a big enum. As default, Swift requires all switch statements to be exhaustive and will give you a compile error if it is not. To fix this error, you could add every case to your switch statement, or add a default case, which says: If the available cases do no match, use my default case. Which is great, but when you add a new case, you can forget to add logic for this case in your switch statement because you added a default case. This can result in painfully debugging what went wrong, only to find out you forgot to update your switch statement.

Luckily, Swift 5 offers a new way with the @unknown property! When you add this property before your default case, any new cases you will add in the future, or cases that are not added yet, will give a compile warning to notify you that your switch statement is not exhaustive. This is a great feature because the compiler will help you but not as aggressive since your code does not break.

Xcode warning showing "Switch must be exhaustive" on a custom made enum.
In Swift < 5, this was not giving a warning.

Thanks to Swift 5, you now have more choices how you would write your switch statements and make it somewhat future proof. Do not forget to add the @unknown property to your existing switch statements where you added a default case!

If you want to lookup this proposal, you can find it here: https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md