Extensions in Swift 3.0


As the previous post I  explained Protocol.  So What's new here? Today I wrote about Extensions, very powerful in swift. 

Extensions :- 

If you are familiar with objective c “Category” then digest this swift concept is simple. It serves the almost same purpose. 
Extensions allow us to add additional functionality to an existing class structure and enum type. Which adds the power of extends type for which class you do not have access to original source code, the process know as Retroactive Modelling. We use “extension” keyword to create the extension.

extension TestClass {

}

Note that to define extensions, we use the extension keyword followed by the type we would like to extend.  Even we can create the extension inbuilt class, String, Array, etc.

Extensions Functionalities:

Extensions with Protocol conformance:-

you can extend an existing ‘type’ to adopt and just to conform new protocol even you do not have the original class of ‘type’.

extension SomeClass: Protocol1,protocol2 {
    
}
Extension in swift can add computed instance properties and computed type properties:-

Extensions can add computed instance properties and computed type properties to existing types.
extension Double {
    var kg: Double { return self / 1000.0 }
    var gm: Double { return self * 1000}
}

let onekilo = 1.0.gm
print("One kilo is \(onekilo) gm”)

Extensions used with Protocol:

If any type conforms all the requirements of protocol but not mentioned in written, then we can use empty extension: to adopt the protocol.

protocol Printable {
   func  showMessage() -> String
}

So that means if any type implement the above method and does mention the conformance of protocol then we can do conformance with empty extension 

extension SomeClass: Printable { } // empty extension

Note: Type does not automatically adopt the protocol just satisfying the requirement, it must mention separately in written. Means Protocol Printable has one method as show Message, if any type implements same method and that type does not 
states by writing it then it does not mean that type has to conform it, it has to stated separately.



An Extension can add new properties, method and subscript to an existing type.

Computed Properties: Extension can add computed instance properties and computed instance type properties to existing types. This will make your life easier to use existing type in the better way.

extension NSDate {
    var nextDay: NSDate { return self.addingTimeInterval(24*60*60)}
    var previousDay: NSDate { return self.addingTimeInterval(-24*60*60)}
}
var date = NSDate()

let nextDay = date.nextDay
let prevDay = date.previousDay

Initializers:

An Extensions can add new initializers to existing type this gives the ability to other types to use your created types as initializers parameters, this will add extra initialization method which was not there in actual types.
An Extensions can add new different initializer method to class, which is not there in original class. The Class must give the initializers and de initializers by itself.

extension UIColor {
    convenience init(red: Int, green: Int, blue: Int) {
        let red = CGFloat(red)/255
        let green = CGFloat(green)/255
        let blue = CGFloat(blue)/255
        self.init(red: red, green: green, blue: blue, alpha: 1.0)
    }
}

let color = UIColor.init(red: 120, green: 230, blue: 50)

Methods:

Extensions can add new instance methods and type methods to existing types. The following example adds a new instance method called full name to the String type:
extension Int {
    func repetitions(task: () -> Void) {
        for _ in 0..<self {
            task()
        }
    }
}

Uses: 
3.repetitions {
    print("Hello!")
}
// Hello!
// Hello!
// Hello!

Mutating Instance Method:

Instance method added to Extensions can also mutate the instance itself. Structure and method which modify itself or properties must mark with mutate keyword.

extension Int {
    mutating func cube() {
        self = self * self *self
    }
}

var myInt = 3
myInt.cube() //27


Subscripts :

Adding new subscripts to already declared instances can also be possible with extensions.

extension Int {
    subscript(changeable: Int) -> Int {
        var muttable = changeable
        var no1 = 1
        while muttable > 0 {
            no1 *= 10
            muttable -= 1
        }
        return (self / no1) % 10
    }
}

print(12[0]) // returns 2

print(12[1]) // returns 1


Nested Type:

Extensions can add new nested types to existing classes, structures, and enumerations:

extension Int {
    enum type {
        case Even, Odd ,Other
    }
    var evenorOddtype:type {
        
        switch (self%2) {
        case 0:
            return .Even
        case 1:
            return .Odd
        default:
            return .Other
        }
    }
}

var myodd = 5
myodd.evenorOddtype // Odd
var myeven = 2
myeven.evenorOddtype // Event
var myother = -1
myother.evenorOddtype // Other

This example adds a new nested enumeration to Int. This enumeration, called type, expresses the kind of Int that a particular Int represents. Specifically, it expresses whether the Int is  Even, Odd or whether it is another kind of Int. This example also adds newly computed instance property to Int, called type, which returns the appropriate type enumeration member for that Int.



That's all fom Extensions in swift. Now you are faimilar with Extensions and you
Hope you liked this post. Please, do commnet nd give your valuable suggestions.
Stay tune for next update !!!
Happy Coding :)!!!

















Comments

Popular posts from this blog

Copy Vs Mutable Copy in iOS

How to Disable iOS/iPad App availability on Mac Store, Silicon?

Functions in Swfit 3.0