O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Extensions

With extensions, we can add new properties, methods, initializers, and subscripts, or make an existing type conform to a protocol without modifying the source code for the type. 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required