Use Extension in Swift

· 1 min read
Use Extension in Swift

Extension is a great feature in Swift, which can help us to create helper/utility variables and method, and etc.

Use extension to conform protocols

It is quite common to use protocols in any project, with extension, we can make the code more organized.

extension CollectionViewController: UITableViewDelegate, UITableViewDataSource {    
	// necessary methods implementation
}

In the above code, we make CollectionViewController conforms the protocol UITableViewDelegate and UITableViewDataSource.

Add new properties to existing struct/classes

To be more specific, we can add computed property to the current existing classes.

Example: we can get an UIView's position information such as x, y, width and height easily.

// old way
view.frame.size.width
view.frame.size.height
view.frame.origin.x
view.frame.origin.y

// use extension
extension UIView {
    var x: CGFloat {
        set {
            self.frame.origin.x = newValue
        }
        get {
            return self.frame.origin.x
        }
    }
    
    var y: CGFloat {
        set {
            self.frame.origin.y = newValue
        }
        get {
            return self.frame.origin.y
        }
    }
    
    var width: CGFloat {
        set {
            self.frame.size.width = newValue
        }
        get {
            return self.frame.size.width
        }
    }
    var height: CGFloat {
        set {
            self.frame.size.height = newValue
        }
        get {
            return self.frame.size.height
        }
    }
}

// after the definition above, so we can use the following instead
view.x
view.y
view.width
view.height

Add new methods to existing structs/classes

This is most commonly used functions in daily development, the following is the UIColor extension which convert a Hex color into UIColor, note that we don't have the source code on UIColor.

import Foundation
import UIKit

extension UIColor {
    
    // Allow UIColor to use the Hex string
    // e.g. UIColor.init("445577")
    public convenience init(hex: String) {
        let scanner = Scanner(string: hex)
        scanner.scanLocation = 0
        
        var rgbValue: UInt64 = 0
        
        scanner.scanHexInt64(&rgbValue)
        
        let r = (rgbValue & 0xff0000) >> 16
        let g = (rgbValue & 0xff00) >> 8
        let b = rgbValue & 0xff
        
        self.init(
            red: CGFloat(r) / 0xff,
            green: CGFloat(g) / 0xff,
            blue: CGFloat(b) / 0xff, alpha: 1
        )
    }
}

// To use
UIColor.init("445577")