Extension in swift

Tricks to impress your coding crush

Tony Wilson jesuraj
IVYMobility TechBytes
4 min readJun 8, 2020

--

The extension is like magic in swift. The example is two types of persons in your company, one gets a salary per minute and another per hour. So for hours calculation, you have code but not for minutes.

original code

So you need to add the calculation for mins too in this code but not allowed to change anything in original code or no subclasses. At that time just need to go with the extension. (note: for 1 min salary is 100, for 1 hour 1000 just an example )

What the hell is happening here?. When you compile the swift code The original class and its respective extensions are merged.

Now you can easily understand below definition

What is Extension?

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

How to declare an extension for class, protocol, struct, or to subscripts.

  • Just keep the same name for the type you need and for an extension.

syntax

Others way to use extension

Computed Properties

Computed Properties

These properties are computed properties read-only, and so for brevity, they have expressed without the keyword get. Its return value is of type Int and can be used wherever an Int is recognized in mathematical calculations

Here .min used to calculate salary in min and .hour for in an hour.

Nested Types

Extensions can also add new nested types to existing enumerations

Here no need to explain you know what happens here

Methods

You can also use extension for normal func and for mutating func

methods in extension

Not only Method you can also use Subscripts, Nested Types.

Initializers

  • In extensions, deinitialisers are not possible.
  • Extensions for classes can add new convenience initializers. Designated Initialisers for classes must be present in the class implementation only.

Class

Struct

In Struct init take place default but when using initializers we cant set a default value. Don't worry we have EXTENSION with it, we can set a default initializers. Example

Look don't give any name while passing but its say A boy has no name. That is the power of extension

same way for protocols

same, I don't pass any age but when I call age I can get 20 as an answer because I declared default value for age in the protocol

These all offered by extension to us

  1. Add computed instance properties and computed type properties
  2. Define instance methods and type methods
  3. Provide new initializers
  4. Define subscripts
  5. Define and use new nested types
  6. Make an existing type conform to a protocol

I hope you got more about an extension and what you need. Any doubt come lets chat at twitter.

--

--