Continuing on the concept of safe code, and how we can use Swift enums to achieve that, in this blog post I will try to demonstrate an application of this concept coupled with a new feature of Swift 4, which allows the encoding and decoding of JSON objects with almost zero glue code – because let’s be honest: we all hate writing glue code.
If you have been programming for a while, especially for iOS, you’ve probably built plenty of View Controllers. The joke goes that ‘MVC’ actually stands for “Massive View Controllers”. The reason is that it is very easy to just put a lot of code inside view controllers, making them absolutely humongous.
I will not teach you how to fix that now, because that’s especially tricky, but I’m going to give you a short hint that might help you make that whole mess a lot more reliable.
Swift utilizes a concept borrowed from type theory called “Option type”. What it means is that a variable of a certain type can be also declared to be “optional”. In other words, it may have a value set to it, or maybe not. The program will have to check this every time it tries to read the value of this variable.
“But why do you need this??” you might ask. Well, that’s a long story. So let’s get straight to it:
A little bit of history
The year was 1965. A computer scientist, Tony Hoare, was working with colleague Niklaus Wirth on designing a new programming language: Algol W. It was based on (and intended to replace) Algol 60, a successful programming language introduced in 1958 and later updated in 1960. Algol W was designed to include many advanced features such as debugging, profiling, and typed pointers (all three new concepts, and extremely innovative at the time). However, one thing was missing…