0
0
Swiftprogramming~5 mins

Adding initializers via extension in Swift

Choose your learning style9 modes available
Introduction
Extensions let you add new ways to create objects without changing the original code. This helps keep your code clean and organized.
You want to add a new way to create an object without touching the original class or struct.
You need a shortcut to create an object with some default or calculated values.
You want to keep your initializer code separate for better readability.
You are working with a type from a library and cannot change its original code.
Syntax
Swift
extension TypeName {
    init(parameters) {
        // initialize properties
    }
}
You can add convenience initializers to classes and new initializers to structs via extensions.
Extensions cannot add designated initializers to classes, only convenience initializers.
Examples
Adds a new initializer to Point that sets x and y to zero.
Swift
struct Point {
    var x: Double
    var y: Double
}

extension Point {
    init() {
        self.x = 0
        self.y = 0
    }
}
Adds a convenience initializer to Rectangle to create a square.
Swift
class Rectangle {
    var width: Double
    var height: Double
    
    init(width: Double, height: Double) {
        self.width = width
        self.height = height
    }
}

extension Rectangle {
    convenience init(squareSide: Double) {
        self.init(width: squareSide, height: squareSide)
    }
}
Sample Program
This program adds two initializers to Circle: one with no parameters that sets radius to 1.0, and one that takes diameter and calculates radius. It then creates two circles and prints their radii.
Swift
struct Circle {
    var radius: Double
}

extension Circle {
    init() {
        self.radius = 1.0
    }
    
    init(diameter: Double) {
        self.radius = diameter / 2
    }
}

let defaultCircle = Circle()
let bigCircle = Circle(diameter: 10)
print("Default circle radius: \(defaultCircle.radius)")
print("Big circle radius: \(bigCircle.radius)")
OutputSuccess
Important Notes
When adding initializers in extensions, you must fully initialize all properties before use.
For classes, use 'convenience' keyword for initializers added in extensions.
Extensions cannot add stored properties, only computed properties and initializers.
Summary
Extensions let you add new initializers without changing original code.
Use extensions to add convenience initializers to classes and new initializers to structs.
This helps keep code organized and adds flexible ways to create objects.