Express Either–Or-Relationships as Enums

If you want to encapsulate the notion of “either A or B” (also called “lifting” in functional parlance), an enum type in Swift is the best fit: You can use associated values to wrap types with enums, too: These things seem to be expressible through a common ancestor type or protocol. But bananas and apples can be modeled in totally different manners (apart from sharing nutritional value, for example).

Continue reading …

I love Swift's Expressiveness

Take optionals, for example. Optionals demarcate when something’s not there at all. When an optional is nil, this may signify something went wrong. That’s much more explicit than relying on a convention like returning -1 for failed requests. This is convenient and changes the game of handling edge cases completely. Because whenever you receive an optional, you have to deal with its two-fold nature. Checking for -1 can slip your mind. Forgetting to unwrap an optional is unlikely.

Continue reading …