Close modal

Blog Post

Swift Extension for Syntax Candy I - Booleans

Development
Wed 18 May 2016
0 Comments


Rationale

Code just doesn't have to function beautifully - it has to look beautiful too. Swift is a very powerful language and here we will look how to turn booleans into something more object-looking for manipulation and also see how we can create code that conveys our intent and thoughts even more explicitly.

Usage

A typical use case

Old reliable boolean, it serves us well and nothing can change the simplicity, bool is either true or false, or unknown if you use an optional boolean?.

Consider a class for a light switch which holds information about the state of the switch

class LightSwitch {
    var lightSwitch: Bool

    init(initial: Bool) {
        lightSwitch = initial
    }

    func flip() {
        lightSwitch = !lightSwitch
    }
}
The Ugly

So it's either on or off, as seen above we can set internally it by going:

lightSwitch = !lightSwitch

Now that's not a bad option, but if you're like me, having the same expression as both an lvalue and rvalue without anything else may seem a bit superfluous. Bare in mind swift no longer allows lightSwitch ^= true (which isn't much better). So enter extensions and let's see what we can do.

Mutating extensions to the rescue
public extension Bool {
    public mutating func toggle() {
        self = !self
    }
}

Ok, that seems simple enough - but let's see how it works in practice.

class LightSwitch {
    var lightSwitch: Bool

    init(initial: Bool) {
        lightSwitch = initial
    }

    func flip() {
        lightSwitch.toggle()
    }
}

As you can see in a playground by running it, the light will indeed be true after execution of the second line. while it may not seem like a huge deal as there is no lines removed, what it does is make the boolean appear more like an object (which in swift terms it really kind of is), and so we treat it as such, performing a method on it.

Conclusion

Whilst it is just opinion what looks neater or clearer, I think it's fairly safe to say that being able to treat the boolean more like an object and making the manipulations more like actions just adds a level of explicitness which is always a goal to strive for when writing code in today's world of reusable and interoperating modules. ]