One of Swift’s greatest features, and one of my favorites, are enums with associated values. The language itself uses them for its fundamentals, like
Optional<T>, which either has a
.some(T) or is
.none. Another example is the new since Swift 5
Result<T, E>, which either contains a
.success(T) or a
.failure(E) case. In this post, we will go over cases (no pun intended) where an enum is more suitable than a struct or class, and also learn how one can make enums with associated values conform to Codable, achieving a better and safer usage of these data representations when they need to be encoded and decoded. You can scroll to the end of the post to get the final playground.
Enums with associated values make sense when a type may hold only one value, instead of two or more optional values. A classic example for Result is a network operation, which might return either an error or an object. They never should be nil or not be nil simultaneously: when one is nil, the other should exist.
//in this case, the caller must check for nil for both values