Thursday, April 20, 2017

Naming Swift Extensions

David Owens II:

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.

There are several different options, none of them ideal. With Objective-C, you would actually see @implementation Raptor (BirdOfPrey) in the Document Items pop-up menu in Xcode. As far as I can tell, there’s no way to get the Swift type name and category name into a single menu item like that. I have been using:

extension Raptor { // MARK: BirdOfPrey
    // new cool stuff here
}

To me, this adds the least noise while also making the category name stand out a bit in the source. BirdOfPrey will also show up in the menu, indented under Raptor.

Previously: Swift Type Aliases.

Comments RSS · Twitter

Leave a Comment