Wednesday, December 16, 2015 [Tweets] [Favorites]

Swift Type Constrained Extensions

Matt Long:

One of Swift’s most expressive and powerful features is type constrained extensions. If you’re new to Swift coming from Objective-C, think of it as a category in Objective-C yet with the ability to specify type criteria so that your category (extension) only applies to the class if it conforms to a certain type. For example, if you have an array of your own custom objects, you can create functions that are specific to an array of your objects.

His JSON example seems like a bit much, but I like the idea of extending collections with helpers for particular types. Because of the type system, this doesn’t pollute the namespace, and you will get relevant code completions from the IDE. In Objective-C, I would use a free function (with the type in its name) or a class method, both of which are more cumbersome.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment