🎉 End-of-year Sale! Save 25% when you subscribe today.
There is a wonderful correspondence between Swift’s type system and algebra that we are all familiar with from grade school. By understanding this correspondence we can understand our data structures at a much higher level, and this allows us to remove invalid states from our types, thus making things we want to be impossible, actually impossible.
Using algebraic data types as our guiding light we are able to model a collection type in Swift which is compiler-proven to be non-empty. That is, you are not allowed to construct an instance of this type unless you prove that it contains at least one element.
Once you see that enums and structs correspond to addition and multiplication from algebra, and therefore are deeply related concepts, you might wonder what else is there to their connection? Well, quite a bit, and we have an entire collection of episodes dedicated to discovering more about what unites enums and structs: