Swift Extensions

In swift, Extension is the process of extending the functionality of an existing classes, structures, enumerations or protocol types by adding a new functionalities.

 

By using extensions we can extend the functionality of types which we don’t have access to the original source code. In swift, extensions can provide the following functionalities.

 

  • It can add a computed type instance properties
  • It can define an instance and type methods
  • Define a new nested types and subscripts

Generally, in swift we use extension keyword just before the classstructure or enumeration to extend the functionality based on our requirements.

Swift Extension Syntax

Following is the syntax of defining an extensions using extension keyword in swift programming language.

 

extension NameofType {

//New functionality and types

}

Extensions also extend to adopt one or more protocols. After declare of extension type we can inherit protocols using semicolon (:) sign and multiple protocols can be separated by commas (,).

 

extension NameofType: Protocol1, Protocol2 {

//implementation of protocol

}

Swift Extension Example

Following is the simple example of swift extension in which we added a new method to concatenate the two strings.

 

extension String {

var result : String { return self + self }

}

let result = "Trishika " + "Dasari"

print(result)

If you observe above example we are extending the functionality of String using extension keyword to concatenate strings.

 

When we run above program in swift playground we will get result like as shown below

 

Trishika Dasari

This is how we can extensions in swift programming language to extend the behaviour of built-in data types, classesstructures or enumerations based on our requirements. 

Swift Extend Computed Properties

Computed properties are those properties which are calculated each and every time in our code but can’t store the value. These type of properties are used in classesstructures and enumerations. Extensions allow user to add computed properties and computed type properties in the class.

 

Following is the example of extending the functionality of built-in Int data type by adding computed properties.

 

extension Int {

var addition : Int {return self + 30 }

var subtraction : Int {return self - 15 }

var multiplication : Int {return self * 30 }

var division : Int {return self / 5 }

}

let add = 90.addition

print("Addition: \(add) ")

let sub = 50.subtraction

print("Subtraction: \(sub) ")

let mul = 10.multiplication

print("Multiplication: \(mul) ")

let divs = 500.division

print("Division: \(divs) ")

If you observe above example we are extending the functionality of built-in Int data type by adding a new computed properties using extension keyword.

 

When we run above example in swift playground we will get result like as shown below.

 

Addition: 120

Subtraction: 35

Multiplication: 300

Division: 100

This is how we can extend the computed properties in swift programming language based on our requirements.

Swift Extend Initializers

In swift, Initializers are the methods which will call directly when we create an instance of class and we don’t need a dot operator to access it. We can easily add a new initializers in existing class using extensions. This enable us to add a new types or extend own custom types with an initializers parameters and also provide a new additional initialization options that are not included in original implementation type.

 

Extensions can add a new initializers (init) to the class but they cannot add a new deinitializers (deinit) to the class because deinitializers must always be provided by the original class implementation.

 

Following is the example of extending the functionality of initializers using extension keyword in swift programming language.

 

struct temperature {

var t1 = 34

}

struct conversion {

var temp = temperature()

}

extension conversion {

init (tem: temperature){

let result =  (tem.t1 - 32) * 5/9

self.init(temp: temperature(t1: result))

}

}

let t2 = conversion(tem: temperature(t1: 100))

print(t2.temp.t1)

If you observe above example we are extending the structure conversion by adding a new initializer using extension keyword.

 

When we run above example in swift playground we will get result like as shown below.

 

37

This is how we can extend the functionality of initializers in swift programming language.

Swift Extend Methods

In swift, by using extension we can extend the behavior of methods by adding a new instance methods and type methods to existing types.

 

Following is the example of adding new instance method Repeat to the built-in Int data type in swift programming language.

 

extension Int {

func Repeat(Work: () -> Void) {

for in 0..<self {

Work()

}

}

}

3.Repeat {

print("Welcome to Tutlane")

}

If you observe above example we are extending the behavior of swift built-in Int data type by adding a new function Repeat(). After defining an extension, we can call the Repeat() function on any integer to perform a task that many number of times.

 

When we run above program in swift playground we will get a result like as shown below

 

Welcome to Tutlane

Welcome to Tutlane

Welcome to Tutlane

This is how we can extend the behaviour of the methods by using extension in swift programming language.

Swift Mutating Instance Methods

The instance methods which added with an extension can be modify or mutate the instance itself.

 

Structure and enumeration methods that modify self or its properties must mark the instance method as mutating, just like mutating methods from original implementation.

 

Following is the example of mutating instance methods using extension keyword in swift programming language.

 

extension Int {

mutating func multiplication() {

self  = self * self

}

}

var intVal = 10

intVal.multiplication()

print("Multiplication: \(intVal)")

If you observe above example we are extending the behavior of swift built-in Int data type by adding a new mutating function multiplication. After defining an extension, we can call the multiplication function on any integer to perform a task to calculate multiplication of number.

 

When we run above example in swift playground we will get result like as shown below.

 

Multiplication: 100

This is how we can mutate instance methods using extensions in swift programming language.

Swift Extend Subscripts

In swift, Subscript is shorthand way to access the elements in an array, dictionaries and etc. We can define a Subscript in classesstructuresenumerations. Using subscript, we can directly access or set the value any variable without any need of special kind of method. We can also define multiple subscript in single type and also set the multiple parameter for input. By using extensions we can add a new subscript to our existing class type. 

 

Following is the example to add a new subscript in swift built-in Int type. The defined subscript [n] will return the decimal digit from the right of number.

For example we use define number as 12345[1], it will return a 4.

 

extension Int {

subscript (Index: Int) -> Int {

var base = 1

for in 0..<Index {

base *= 10

}

return (self / base) % 10

}

}

print(23[0])

print(1456789[2])

print(654321[3])

If you observe above example we added an integer subscript to swift’s built-in int data type and the subscript[n] will return the decimal digit n places in from the right of the number.

 

When we run above example in swift playground we will get a result like as shown below.

 

3

7

4

This is how we can add a new subscripts to our existing class type using extensions in swift programming language.

Swift Extend Nested Types

In swift we can add new nested types to our existing classstructure or enumeration using extensions.

 

Following is the example of using extension to extend the existing class by adding nested types.

 

enum Tutorials {

case book(title: String, author: String, year: Int)

}

extension Tutorials {

var Title: String {

switch self {

case .book(title: let aTitle, author: _, year: _):

return aTitle

}

}

}

let book = Tutorials.book(title: "iPhone App Development", author: "Suresh Dasari", year: 2017)

print(book)

If you observe above example we are adding new nested type in existing class “Tutorials” using extension keyword.

 

When we run above program in swift playground we will get a result like as shown below

 

book("iPhone App Development", "Suresh Dasari", 2017)

This is how we can use extensions to add nested types in existing classes based on our requirements in swift programming language.