Swift introduced some new language features to the iOS and OS X developers toolbox. It also gave new names to old features. Blocks are now Closures and Categories are now Extensions.

Swift Extensions add functionality to an existing class without introducing hierarchy. It can extend classes, structures or enumeration types. Unlike Objective-C Categories, Extensions are not named. The main reason you would want to use Extensions is to add behaviour to a type you don’t have access to. A classic example would be adding extra colors to UIColor. We already have class methods for conveniently creating redColor and purpleColor, but we don’t have one for pink. Let’s make it:

import UIKit

extension UIColor {
  class func pinkColor() -> UIColor {
	   return UIColor(red: 1.0, green: 0.412, blue: 0.706, alpha: 1.0)
	}
}

We use it the same way we use the built-in methods.

self.view.backgroundColor = UIColor.pinkColor()

Keep in mind, that Extensions can only add new functionality. They cannot change existing behaviour.

Extensions can be a powerful tool, but the best way to use them is to keep them as focused and simple as possible.

You can find the example code on GitHub.