| Start |
|---|
| What are Extensions? Extensions (opens new window) are used to extend the functionality of existing types in Swift. Extensions can add subscripts, functions, initializers, and computed properties. They can also make types conform to protocols (opens new window). Suppose you want to be able to compute the factorial (opens new window) of an Then you can access the property just as if it had been included in original Int API. |
| Variables and functions Extensions can contain functions and computed/constant get variables. They are in the format To reference the instance of the extended object, To create an extension of Extensions can also contain |
| Initializers in Extensions Extensions can contain convenience initializers. For example, a failable initializer for |
| Protocol extensions A very useful feature of Swift 2.2 is having the ability of extending protocols. It works pretty much like abstract classes when regarding a functionality you want to be available in all the classes that implements some protocol (without having to inherit from a base common class). This is also possible using generics. |
| Subscripts Extensions can add new subscripts to an existing type. This example gets the character inside a String using the given index: |
| Restrictions It is possible to write a method on a generic type that is more restrictive using where sentence. Example of use |
| What are extensions and when to use them Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code. Extensions in Swift can:
When to use Swift Extensions:
When not to use:
Simple example: RemarksYou can read more about extensions in The Swift Programming Language (opens new window). |
Read Article
https://develop.horje.com/learn/1434/reference