Site icon CodeWithSwift

Extensions

Extensions in Swift are a powerful feature that allows you to add new functionality to an existing class, struct, enum, or protocol without modifying the original source code. Extensions can add methods, computed properties, initializers, and even conform types to protocols.

Syntax

extension TypeName {
    // New functionality here
}

Adding Computed Properties

Extensions can add computed properties, but not stored properties.

extension Double {
    var square: Double {
        return self * self
    }

    var cube: Double {
        return self * self * self
    }
}

let number: Double = 3.0
print(number.square)  // Output: 9.0
print(number.cube)    // Output: 27.0

//

extension String {
    func reversedString() -> String {
        return String(self.reversed())
    }
    
    func isPalindrome() -> Bool {
        return self.lowercased() == self.reversedString().lowercased()
    }
}

let word = "Radar"
print(word.reversedString())  // Output: radaR
print(word.isPalindrome())    // Output: true

Adding Methods

We can add new instance or static methods to existing types.

extension String {
    func reverse() -> String {
        return String(self.reversed())
    }
}

let name = "Swift"
print(name.reverse())  // Output: tfiwS

Adding Initializers

Extensions can define new initializers for a type. However, you cannot add initializers to existing classes if they already have custom initializers defined.

struct Point {
    var x: Double
    var y: Double
}

extension Point {
    init(value: Double) {
        self.x = value
        self.y = value
    }
}

let point = Point(value: 5.0)
print(point)  // Output: Point(x: 5.0, y: 5.0)

Extending Protocol and Default Implementation

Extensions can add functionality to protocols, allowing conforming types to inherit default behaviour.

protocol Greeting {
    func sayHello()
}

extension Greeting {
    func sayHello() {
        print("Hello, world")
    }
}

struct Person: Greeting {}
let person = Person()
person.sayHello()  // Output: Hello, world
Exit mobile version