Monday 1 October 2018

Extensions

Extensions means add additional functionality to existing types.
Extensions add new functionality to existing class, struct, enum or protocols.
Extensions are similar to categories in Objective-C.

Extension syntax
Declare Extension with "extension" keyword

extension Type {
    ///Additional functionality add hear

}

An Extension can extends one or more protocols.

extension Type : Protocol{
    ///protocols method hear
}

Example

extension String{
    ///Trim string value
    func toTrim() -> String{
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}

///Simply use like below
let strName = " use of string extension "
print(strName)
print(strName.toTrim())

Output : 

 use of string extension 
use of string extension

Another example

extension UIView {
    func defaultRadius() {
        self.layer.cornerRadius = self.frame.size.width / 2
    }
}

let parentView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 50, height: 50))
parentView.backgroundColor = UIColor.red
parentView.defaultRadius()

Output: 

UIView Extension


Computed Properties

Extension can add computed instance property and computed type property to existing type.

Example

extension Int{
    var squareRoot : Int {
        return self * self
    }
}

let iValue = 5
print(iValue.squareRoot)

Output : 

25

Methods

Extensions add new instance method and type method to existence type.

Example

extension Int{
    func repeatValue(value : () -> Void) {
        for _ in 0..<self{
            value()
        }
    }
}

5.repeatValue {
    print("hello world")

}

Output :

hello world
hello world
hello world
hello world
hello world

For more about Extensions watch below video



No comments:

Post a Comment