Imagine we’re creating a Mood App: an app that let’s users record how they’re feeling. Obviously our app’s users are constantly happy, excited or pensive seeing as they are totally aware of how blessed they are to live in such an exciting time with everything at their fingertips 😀

Let’s say we wanted to store the state of their mood at any one time. How would you go about that? Well traditionally enums were great for storing a group of related data, however Swift really levelled up enums in so many ways that I can’t cover them in one post. One of the amazing things though is to store state in a way that is more useful and detailed than just a simple value.

Imagine we wanted to store the user’s current mood from a selection and whether or not they’ve had a coffee yet. This information is vital for scientific research on the impact of caffeine on the brain:

struct Mood {
    enum CurrentMood {
        case Happy(reason: String?, didHaveCoffee: Bool)
        case Excited(reason: String?, didHaveCoffee: Bool)
        case Pensive(reason: String?, didHaveCoffee: Bool, areDayDreaming: Bool)
    var userMood: CurrentMood

We’ve created a value type (a struct) and an enum called CurrentMood. It stores the two properties along with the states: Happy, Excited and Pensive. This is super-useful because the scientists who are studying the behaviour of the potentially caffeinated programmers need to know both bits of info at the same time. You can see with the Pensive state we’ve added the totally necessary ‘are you sure you’re not daydreaming check’ to the state as well, just to show that you can have different patterns when matching the data: hence the term ‘Pattern Matching’ with enums.

Let’s create a simple user struct:

struct User {
    var userMood: Mood.CurrentMood
    init(with mood: Mood.CurrentMood) {
        self.userMood = mood

The user has a mood state that we’re going to switch now and then and a simple init, which we don’t technically need to write due to the memberwise initialiser built into structs, but it helps make things a little clearer for the scientists who are struggling to keep up with all the data pouring in.

var interestingUser = User(with: .Excited(reason: "Starting new job", didHaveCoffee: true))
interestingUser.userMood = .Happy(reason: nil, didHaveCoffee: true)

Here we’ve instantiated our user and set their mood. Notice the cool optional value for ‘reason’ for happiness. Do you really need a reason? Not really, but I’m sure you can think of some reasons! The great thing about optionals is that they can either be nil or a value and they work well in this situation.

Hopefully you can see the value in pattern matching with swift enums with this super-simple example.

Leave a Reply

Your email address will not be published. Required fields are marked *