21 Extensions

Imagine that you are developing an application that uses a particular type in the Swift standard library – say the Double type – quite frequently. It would make your development easier if the Double type supported some additional methods based on how you are using it in your app. Unfortunately, you do not have Double’s implementation available, so you cannot add functionality directly to it yourself. What can you do?

Swift provides a feature called extensions that is designed for just these cases. Extensions allow you to add functionality to an existing type. You can extend structs, enums, and classes.

You can use extensions to extend types with:

  • computed properties

  • new initializers

  • protocol conformance ...

Get Swift Programming: The Big Nerd Ranch Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.