Swift - Custom Type Extensions

Introduction

In Swift, you can extend existing types and add methods and computed properties.

This is the general preferred way to add new functionality to a class, rather than inheritance.

You can add functionality to exising class.

Or you want to divide its functionality into different sections for readability.

In Swift, you can extend any type: your own type and built-in types.

To create an extension, you use the extension keyword, followed by the name of the type you want to extend.

Once you extend a type, the methods and properties you defined in the extension are available to every instance of that type.

For example, to add methods and properties to the built-in Int type, you can do this:

Demo

extension Int { 
    var double  : Int { 
        return self * 2 
    } //from  w w w. j  a va 2  s . c  o  m
    func multiplyWith(anotherNumber: Int) -> Int { 
        return self * anotherNumber 
    } 
} 

print(2.double) // 4 
print(2.multiplyWith(anotherNumber: 5)) // 10

Result

Related Topics