There’s a lot of talk about how extensions are used for code organization. This is even one of the primary defenses for some of the Swift proposals. However, it’s missing a key component of organization: categorization.
If you remember when dinosaurs roamed the Earth, they wrote code to maneuver their space ships with a language that must have been from aliens: Objective-C.
If you wanted to extend a type and provide yourself some new goodies, you would do so like this:
@implementation Raptor (BirdOfPrey) // new cool stuff here @end
In Swift, however, it’s not as clear what we should do.
Comments
Ok, this is the easiest and most straight-forward way do it. It’s close to what we had before. But as a comment, it has a bit of disconnect from the type. If you’re like me, you’ve also trained yourself to skim over comments like ads on a website.
extension Raptor /* BirdOfPrey */ { // new cool stuff here }
Protocols
Now, of course, I think the most illustrious Swifters would say, “Obvious: use a protocol.”
Yep, you could do that:
protocol BirdOfPrey {} extension Raptor: BirdOfPrey { /* ... */ }
And that’s not too bad, but you’ll implement it one of two ways:
- An empty protocol as you simply don’t care about duplicating the signatures for a one-off categorization mechanism.
- A full on protocol, because you’re a good little dinosaur offspring!
However, unless you’re going to be reusing these protocols, both are simply noise that you’re adding to the system that is supposed to simply help you organize your code.
Typealias
Another approach that was mentioned on Twitter:
Honestly, I’d not thought of this approach.
typealias RaptorBirdOfPrey = Raptor extension RaptorBirdOfPrey { // new cool stuff here }
I’m not personally a fan of this as it confuses the type some and introduces just as much noise as the empty protocol, but with more downsides, in my opinion.
Do Nothing
Of course, this is also an option too. Simply do nothing. Sadly for my code, this is often what I end up doing.
Wait A Minute…
I know what some of you are thinking… didn’t we have to define these categories in a .h file so we could use them?
Yes. If you wanted to use them outside of the file, that’s 100% correct. Thanks C.
But! Swift doesn’t have header files so we should not have to be burdened with all this duplicate declaration stuff… but, in this case, we still kind of are if we want to go the protocol route.
It would be great if we could just do this:
extension Raptor (BirdOfPrey) { // new cool stuff in our implicit protocol: BirdOfPrey }
[…] David Owens II: […]
LikeLike