Extensions

With extensions, we can add new properties, methods, initializers, and subscripts, or make an existing class or structure conform to a protocol. One thing to note is that extensions cannot override the existing functionality.

To define an extension, we use the extension keyword, followed by the type that we are extending. The following example shows how we would create an extension that extends the string class:

extension String {
  //add new functionality here
}

Let's see how extensions work by adding a reverse() method and a firstLetter property to Swift's standard string class:

extension String { var firstLetter: Character { get { return self.characters.first } } func reverse() -> String { var reverse = "" for letter in self.characters ...

Get Mastering Swift 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.