Swift – (more) concise

hsoi blog, talk 0 Comments

You have to use Apple’s new Swift language to really appreciate it. Or at least, it certainly helps.

I was reading this article on Swift State Machines. The article itself is great because it shows how you can take advantage of Swift’s unique features and power to take a properly-Swift approach to state machine implementation. A key thing in making the switch from Objective-C to Swift is that you have to get yourself thinking in Swift, not thinking in Objective-C and how to translate that to Swift. Sure, that’s how you’ll begin, but over time you have to Think Different, you have to Think Swift.

But what really struck me about the article was this snippet of code:

class StateMachine{
    //We'll define StateType in a moment...
    var state:StateType
        state = initialState

Ignore the specifics of the code and look at what the code tells you. I actually found myself staring at it for a little while appreciating the brevity and elegance of the code vs. all that it told.

A big thing is that the notion of a state is defined as always there (it’s not an optional). This is implied by the pattern of passing the state in the init() method sure. But if this was written in Objective-C, there’s no true enforcement.

That is, in Objective-C, StateType is a simple enum, which winds up being little more than syntactic sugar for an integer. If I wanted to assign a value outside of the enum’s types, while some compiler warnings have come around to help catch that, it’s only a warning and easily circumvented.

Or, what if the state was a class? Then it would wind up being a pointer, which yes could be nil.

The only way to avoid the nil in Objective-C? Well, you’d have to document it:

@property (nonatomic, strong) StateType* state; // must never be nil

Or something to that effect. At best you might be able to help document and contend for it through something like:

- (void)setStateType:(StateType*)newType {
    NSParameterAssert(newType != nil);
    _stateType = newType;

But the assertion only takes you so far. Plus now you have to write this, remember to write it, ensure you wrote it correctly, and a host of other things. The Swift approach, the language, the compiler, the runtime, take care of this for you.

If you want to talk about self-documenting code, certainly the Swift approach winds up being quite self-documenting as well as more concise.

Sure it’s a small thing, but all these small details are what really add up towards making your life and code a lot better on a daily basis.

Leave a Reply