I wrote in August of last year about some potential confusion coming out of the decision to statically dispatch calls to methods defined in a protocol extension that were not defined in the protocol itself. (Whereas calls to methods defined in the protocol are always dynamically dispatched.) This allowed the protocol / extension designer to differentiate between customization points (methods defined in the protocol) and non-customizable code (methods not defined in the protocol, but implemented in an extension).

It looks like Apple’s received some feedback around this, and Doug Gregor acknowledges this is his “Completing Generics” Manifesto. (Update May 5: Austin Zheng has created a formatted version of the manifesto, available on GitHub.) However I’m not optimistic that this will get changed in future versions of Swift, as he puts it in his “Maybe” section:

Maybe

There are a number of features that get discussed from time-to-time, while they could fit into Swift’s generics system, it’s not clear that they belong in Swift at all. The important question for any feature in this category is not “can it be done” or “are there cool things we can express”, but “how can everyday Swift developers benefit from the addition of such a feature?”. Without strong motivating examples, none of these “maybes” will move further along.

Dynamic dispatch for members of protocol extensions

Only the requirements of protocols currently use dynamic dispatch, which can lead
to surprises:

protocol P {
  func foo()
}
extension P {
  func foo() { print(“P.foo()”)
  func bar() { print(“P.bar()”)
}
struct X : P {
  func foo() { print(“X.foo()”)
  func bar() { print(“X.bar()”)
}
let x = X()
x.foo() // X.foo()
x.bar() // X.bar()
let p: P = X()
p.foo() // X.foo()
p.bar() // P.bar()

Swift could adopt a model where members of protocol extensions are dynamically dispatched.

Fingers crossed, but I think the ship has probably sailed on this – I wonder if the change of behaviour would result in more confusing bugs than this quirk of the language did in the first place.


One of the biggest lessons I learned in the fallout of my concussion last year is how important posture is, especially to desk workers like me. Post-Concussion Syndrome has a major muscular component – tight neck and back muscles press against nerves that send confusing signals to your brain, prolonging concussion symptoms like dizziness, fatigue, and visual disturbance. Treatment of this aspect of PCS is fairly standard physiotherapy fare – stretching and strengthening.

One of the most important ways to keep tight muscles from getting out of control is to maintain good posture. Most of us tech workers tend to stay in a very head-forward position, craning toward the screen, shoulders hunched over the keyboard.1

This is a sure way to cause neck and back strain.

Instead, we should be sitting up straight, shoulders down and back, neck straight, and chin tucked in. It feels weird, and it takes a while to get used to. When I’m at my desk with my mind focused on more interesting things I continually forget about maintaining posture. I have a post-it sitting directly above my monitor, and that helped me remember for a while, but now it’s just part of my surroundings and I no longer notice it.

My physiotherapist recommended a periodic reminder to keep me focused on my posture. I wrote a shell script, so that my computer could prompt me from time to time to stop slouching. It runs in the background, and at a random interval,2 it speaks aloud using the say command and posts a notification using terminal-notifier, which you can install as a gem or via Homebrew on a Mac.

max=30
min=6
message="Fix your posture, dummy!"

function randomSeconds {
    range=$(($max - $min))

    rand=$(($RANDOM % $range))

    minutes=$(($rand + $min))
    seconds=$(($minutes * 60))

    echo $seconds
}

while :
do
    seconds=`randomSeconds`
    echo "Sleeping $(($seconds / 60)) minutes"
    sleep $seconds
    terminal-notifier -title "Posture" -message "$message" -group posture-notifier > /dev/null
    say $message
done

And of course, we should all remember to get up and walk around about once an hour. Staying static is actually one of the hardest things for our muscles to do. They’re designed to keep us in motion, so let’s oblige them!

I think I’ll write another post about workstation ergonomics at some point – I see a horrifying array of bad setups wherever I go, and we could all use a little improvement.


  1. We’ve all seen images like this one courtesy of
    The Moxie Institute‘s film Connected.

  2. Our brains are too smart for our own good. If you set up a reminder to go off every twenty minutes, you internalize it eventually and fixe up your posture “automatically” around the time when you expect the reminder. Then, when it arrives, you consciously check your posture, observe that it’s great, and start to slouch again a few minutes later. A randomized reminder keeps you on your toes. 

Handlebars is Logicless

Like, really, really logicless.

Handlebars is the templating system that I chose when writing Concussion, the engine that powers this blog. It’s one of the big names (I’d heard of it even though I’d never done any Node work before) and it has built-in support for Express via handlebars-express. Since it’s obviously so widely used, I figured it would be fine for my purposes. And while everything turned out fine in the end, I had to change the arrangement of responsibilities in my app to get around some unexpected problems, because as it turns out, Handlebars is logicless.1

The README points this out right at the top:

Handlebars.js is an extension to the Mustache templating language created by Chris Wanstrath. Handlebars.js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be.

Which is all it has to say about the matter. Seems reasonable enough. If you’re doing anything approaching MVC, the view should be responsible solely for how the data is presented to the user. It shouldn’t do anything.

Handlebars takes this to a bit of an extreme.

There’s logicless, and there’s Logicless.

I think we can all agree that views (“templates” in Handlebars) shouldn’t directly act on models and shouldn’t implement business logic, but I do think that they should be masters of their own domain when it comes to turning data into something the user can see and interact with. By definition, they are a transform on a set of data. Handlebars recognizes this, and allows you to use all sorts of helper functions. You can include or omit a block of content based on the presence of a certain variable, call a function to properly format a value, or shell out to a sub-view (or “partial”).

What you can’t do is provide an arbitrary JavaScript expression to an if block, although you wouldn’t know it by reading the docs:

You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.

The if block can only accept a value (which could be a variable or the output of another helper). And because you can’t use an expression, you can’t do comparisons.

This should be a requirement of any templating engine.

Maybe I’ve just been spoiled by using PHP in the past, where (at least in CakePHP, the framework I’ve worked in) the templates are just regular PHP files, but I think having the basic ability to perform comparisons is absolutely central to a view’s ability to do its job. I want to be able to show (or not show) a section based on the view’s own choosing, not because a value is truthy or falsey.

Example: Pagination

This is a super simple example. Here’s how I want to accomplish a pagination view:

  • If the current page is greater than 1, show a link that navigates to page current - 1
  • If the current page is less than the number of pages, show a link that navigates to page current + 1

However, in Handlebars I have to do extra work in the controller to accomplish this:

  • If the current page is greater than 1, create a new variable previousPage = current - 1
  • If the current page is less than the number of pages, create a new variable nextPage = current + 1

Then in the template:

  • If previousPage exists, show a link that navigates to page previousPage
  • If nextPage exists, show a link that navigates to page nextPage

In addition to making more steps, this increases coupling between the controller and the view, something we should be always striving to reduce.2

GitHub Discussion

There’s a long and contentious discussion on Handlebars’ GitHub repository. The maintainers of Handlebars are gently sticking to their guns, which is understandable. Some of the commenters on that discussion are extremely dismissive. But there are many commenters who wish for more expressiveness in if blocks. Mike O’Brien sums it up best:

An if helper is there, IT IS LOGIC. So the whole logic-less argument is a total straw man

[…]

I totally agree with and understand not having business logic in templates. But unless you’re doing extremely trivial templates your going to have some view logic there. Handlebars obviously recognizes this since the if helper exists. Working around a hamstringed if helper by adding a bunch of view logic in your code is not the answer […]

Solutions

  • Prepare your data in such a way that your templates don’t need to perform any math or comparisons. This is what I’ve done – basically what I showed in the pagination example.
  • Build an unwieldy set of helpers (or one multi-purpose helper) as shown here.
  • Use a different templating system. EJS and Underscore templates look like good candidates – they read a lot like the PHP templates I’m used to, with all the good and bad that entails. doT also looks nice. Additionally, there are a lot of engines that allow comparisons out of the box but still disallow full access to JavaScript, if that suits your fancy.

Think I’m wrong? Got something to add? Let me know on Twitter!


  1. Although you have to make it to their GitHub README to find out. Their homepage makes no mention of this limitation. 

  2. In this particular example there’s not a huge difference in how coupled things are, but the fact that I had to change what happens in my controller in order to make my view happy irks me enormously. We didn’t need to provide more data, the view just required it to happen in a certain way. That’s coupling. 


For a few weeks I’ve been working on a new iOS app, written in Swift. The problem domain is super simple: it’s just a list of what I’m calling “reminder snippets” – for now, basic Title / Value pairs – that are editable in the app, and show up in a Today View Snippet.

Screenshot of example app, Neumonic

Having the problem domain so small allows me to experiment with Swift and potential architectures. I’ve been incorporating some lessons I learned from colleagues at my last job, like using immutable model objects (Swift structs, naturally, for value semantics) and Repositories that are responsible for persistence, caching, and so on.

Protocols

I took the Protocol Oriented Programming talk from last year’s WWDC to heart, so every abstraction in the app is a protocol. (I’ve already written a bit about this talk here.) Specifically, I have a ReminderRepository protocol (with MockReminderRepository and PlistReminderRepository implementations) and a Reminder protocol, with one incredibly simple implementation.

public typealias ReminderID = String

public protocol Reminder{
    var id : ReminderID { get }
    var title : String { get }
    var value : String { get }
}

public protocol ReminderRepository {
    func getAllReminders(callback: Result<[Reminder]> -> Void)
    func getReminder(by id: ReminderID, callback: Result<Reminder> -> Void)
    func addReminder(reminder: Reminder, callback: VoidResult -> Void)
    func deleteReminder(reminder: Reminder, callback: VoidResult -> Void)
}

(Result is just a Success/Fail enum that contains some value on success and an error on failure)

Equatable

So far, so good. I really like this architecture. But problems start to crop up when I need to be able to compare Reminders, for instance, in an implementation of deleteReminder:

public func deleteReminder(reminder: Reminder, callback: VoidResult -> Void) {
    // Error. Can't call indexOf because reminder doesn't conform to Equatable
    if let index = reminders.indexOf(reminder) {        
        reminders.removeAtIndex(index)
        callback(.Success)
    } else {
        callback(.Failure)
    }
}

But if we make Reminder conform to Equatable, we lose the ability to have a heterogeneous array of types that conform to Reminder. (Details are in the Protocol Oriented Programming talk. Seriously, watch it.)

The solution given in the talk for general-case comparison is to implement an extension on our protocol. I thought I’d be clever and factor this out into a new protocol, HeterogeneousEquatable, and have Reminder extend from that.

public protocol HeterogeneousEquatable {
    func isEqual(other : Any) -> Bool
}

public extension HeterogeneousEquatable where Self : Equatable {
    public func isEqual(other : Any) -> Bool {
        if let typedOther = other as? Self {
            return typedOther == self
        }
        return false
    }
}

public protocol Reminder : HeterogeneousEquatable { /* ... */ }

Array.indexOf()

Now returning to the reason I initially wanted to make Reminders Equatable – so that I can call reminders.indexOf(someReminder). Right now we still can’t do that, because while we have roughly equivalent functionality, it doesn’t come under the auspices of the Equatable protocol.

Okay, so what if we just extend Array ourselves?

public extension Array where Element : HeterogeneousEquatable {
    func indexOf(element : Element) -> Index? {
        return indexOf({ (currentElement : Element ) -> Bool in
            element == currentElement
        })
    }
}

Great! Everything still compiles. Now we just have to call our overloaded implementation of indexOf:

public func deleteReminder(reminder: Reminder, callback: VoidResult -> Void) {
    // Error again. Sad face.
    if let index = reminders.indexOf(reminder) {        
        reminders.removeAtIndex(index)
        callback(.Success)
    } else {
        callback(.Failure)
    }
}

Now we get Using "Reminder" as a concrete type conforming to protocol "HeterogeneousEquatable" is not supported. Which is true. Reminder isn’t a concrete type. This is a shortcoming in the compiler; it needs things to be nailed down to concrete types here. One can assume that the reason for this is compiler implementation rather than an intentional limitation of the language at a design level. There’s a great Stack Overflow answer by Rob Napier on this.

A Mediocre Solution

Austin Zheng has a blog post about building a HeterogeneousEquatable (which he calls AnyEquatable), which is a good resource if you found my post hard to follow, but he doesn’t look at the case of implementing an extension on Array.

I asked about this on the swift-users mailing list, and Hooman Mehr pointed out that the best way to achieve this is to write a method in an unconditional extension on Array:

extension Array {
    func indexOf(element : HeterogeneousEquatable) -> Index? {
        return self.indexOf { (currentElement : Element) -> Bool in
            if let currentElement = currentElement as? HeterogeneousEquatable {
                return element.equals(currentElement)
            }
            return false
        }
    }
}

This makes me sad. It forces me to pollute the interface of Array with stuff that doesn’t apply in most cases, and it causes confusion about which implementation of indexOf will be called in an instance of [MyType] where MyType implements both Equatable and HeterogeneousEquatable. (The other option is to name it indexOfAny, as Hooman suggests, but I don’t much like that either.)

A Better Solution, Sometimes

I took my quest to the swift-evolution mailing list, and got better results, but they only apply in certain situations.

Dave Abrahams (the guy who gave the Protocol Oriented Programming talk in the first place!) showed that while we can’t use a value of type HeterogeneousEquatable (where the concrete type is unknown) where the requirement is Element : HeterogeneousEquatable, we can do that when the requirement is Element == HeterogeneousEquatable. That’s awesome!

But.

That means that the variable must be typed explicitly as HeterogeneousEquatable. Reminder, even though it extends from HeterogeneousEquatable, is not acceptable.

public extension CollectionType where Generator.Element == HeterogeneousEquatable {
    func indexOf(item: Generator.Element) -> Index? {
        return indexOf {
            return item.isEqual($0)
        }
    }
}

// ...

public func deleteReminder(reminder: Reminder, callback: VoidResult -> Void) {
    if let index = reminders.indexOf(reminder) {        
        reminders.removeAtIndex(index)
        callback(.Success)
    } else {
        callback(.Failure)
    }
}

Type HeterogeneousEquatable does not conform to protocol 'Reminder'

Conclusion

I’ve had to go ahead with the unconditional extension of Array. It’s the only thing that works properly for my use case, at least today.

It is my desperate hope that future versions of Swift will allow for this kind of abstraction – or just go ahead and solve the Equatable problem in a first-party way.

Denouement

Back when the WWDC talk was new there was a big kerfuffle in the Apple development community about the problem of heterogeneous collections of things that conform to a single protocol – how the decision to split protocols into “has Self requirements” and “doesn’t have self requirements” worlds was benefiting the compiler at the expense of the programmer. Michael Tsai has a good overview of the various blogs from that time, all of which are worth a read, including this post from Brent Simmons:

Something like this ought to come naturally and easily to a language, or else that language is not helping me write apps.

I’m generally very positive on Swift – I think when Swift 3.0 hits and the language starts to change a little more slowly, it will be the obvious choice for future projects – but it has some sharp edges for the time being, and if I was to start a production-ready project today, I’m not entirely sure whether I’d choose Swift or Objective-C.


Mike Ash’s Friday Q&A this week takes on Swift’s funny-looking String API. Most of what you’d normally want to do with strings is absent — for the time being, we should be using NSString methods — and it doesn’t allow us to iterate over its characters in the way we’d expect. As of Swift 2.0, we can’t do:

for char in "some string" { /* ... */ }

That’s because there are several ways to interpret the above code — do we want to iterate over all bytes in the string, assuming it’s represented as UTF-8? All Unicode code points? All grapheme clusters? The String API’s design in Swift 2 forces the developer to explicitly decide by exposing these possibilities as views on the string, leaving the system’s internal representation of the string as an invisible implementation detail.

From Mike’s post:

Swift’s String type takes an unusual approach to strings. Many other languages pick one canonical representation for strings and leave you to fend for yourself if you want anything else. Often they simply give up on important questions like “what exactly is a character?” and pick something which is easy to work with in code but which sugar-coats the inherently difficult problems encountered in string processing. Swift doesn’t sugar-coat it, but instead shows you the reality of what’s going on. This can be difficult, but it’s no more difficult than it needs to be.

This is an excellent companion to objc.io‘s must-read NSString and Unicode showing the implications for Swift.

If you want the Cole’s Notes version, Apple has a pretty good, much shorter explainer on their Swift blog.