Sum (Coproduct) is alternation (A | B, meaning A or B but not both).
Swift provides some “Sum” built-in types already — such as Optional and Result.
These “Sum” types were added to enable better expressivity/verbosity for certain contexts.
The Optional type allows us to “lift” values up into a world of “nullability”, where we could have “either a value or nothing”.
It is the same thing for the Result type. It lets us live in a world of “success-and-failure” situations, where we could have “either a successful value or a failure”.
The “thing” with these sum types that come in Swift is that they only work when used under the context they were written for.
We cannot use the right side of the Optional type — it is always used to express “nullability”.
We cannot use the right side of the Result type — it is always used to express a “failure”.
Because Either is a Sum type (with a different name), it means that it also is an Applicative Functor and a Monad. In other words, we can do:
Either is a Monad
In our day-to-day activities, we have other situations where we need to wrap values into “specific” contexts based on our business needs. For those kinds of situations, we need an “honest” sum type — the Either type.
For example, nowadays, it is so common to find apps showing personalized ads as part of their content — Facebook, YouTube, Twitter, all of them do that.
Suppose we are developing an app that “loads movies” on the screen, and because of the need for monetizing, we also have to “display ads” between the movies — the monetization service will provide us with a proper response that mixes “Movies and Advertisements” in the same JSON payload.
Recommended Movies response including monetized ads
Keeping this in mind, we may end up with a ViewModel like this:
ViewModel using the Either type
Then, when binding the data into the view, we can easily map and fold.
SwiftUI’s View doing “map” and “fold”
- Either exists in other programming languages such as Haskell and Scala.
- Either is a Sum algebraic data type — also known as Coproduct.
- Either is a Functor — we can do map.
- Either is an Applicative — we can do apply.
- Either is a Monad — we can do flatMap.
- Either allows us to use the right side of the Sum type with freedom — something we cannot do with the Result type.
In case you’d like to have a look: Either type implementation in Swift.
By – Emilio Ojeda, Mobile Architect & Mobile Practice Manager, DigitalOnUs