SoFunction
Updated on 2025-04-11

Detailed introduction to the use of Swift Extension

Extension

1. The extension in Swift is somewhat similar to the classification in OC (Category)

2. Extensions can add new functions to enums, structures, classes, and protocols

You can add methods, computed attributes, subscripts, (convenient) initializers, nested types, protocols, etc.

3. Expanding things that cannot be done

Cannot overwrite the original function

Cannot add storage attributes, and cannot add attribute observers to existing attributes

Cannot add parent class

The specified initializer cannot be added, and the deinitializer cannot be added.

。。。。

extension Double {
    var km: Double {
        self * 1_000.0
    }
    var m: Double {
        self
    }
    var dm: Double {
        self / 100.0
    }
    var cm: Double {
        self / 10.0
    }
    var mm: Double {
        self / 1_000.0
    }
}
var d = 100.0


var arr: Array<Int> = [10, 20, 30]
extension Array {
    subscript(nullable idx: Int) -> Element? {
        if (startIndex ..< endIndex).contains(idx) {
            return self[idx]
        }
        return nil
    }
}
print(arr[nullable: 1] ?? 0)
extension Int {
    func repeats(task: () -> Void) {
        for _ in 0..<self {
            task()
        }
    }
    enum Kind {
        case negative, zero, positive
    }
    var kind: Kind {
        switch self {
        case 0: return .zero
        case let x where x > 0: 
        default: return .negative
        }
    }
    subscript(digitIndex: Int) -> Int {
        var decimalBase = 1
        for _ in 0..<digitIndex {
            decimalBase *= 10
        }
        return (self / decimalBase) % 10
    }
}

Protocol and Initializer

class Person {
    var age: Int
    var name: String
    init(age: Int, name: String) {
         = age
         = name
    }
}
extension Person: Equatable {
    static func == (left: Person, right: Person) -> Bool {
         ==  &&  == 
    }
    convenience init() {
        (age: 0, name: "")
    }
}

1. If you want to customize the initializer, the compiler can also generate the default initializer, then you can write a custom initializer in the extension.

struct Point {
    var x: Int = 0
    var y: Int = 0
}
extension Point {
    init(_ point: Point) {
        (x: , y: )
    }
}

2. The required initializer cannot be written in the extension

protocol

1. If a type has implemented all the requirements of the agreement, but has not stated that it complies with the agreement.

It can be made to comply with this protocol by extension

2. After extending the protocol, anyone who abides with this protocol will have a corresponding extension method. As an example, write a function to determine whether a certificate is an odd number.

extension BinaryInteger {
    func isOdd() -> Bool {
        self % 2 != 0
    }
}

3. Extensions can provide default implementations for the protocol, and indirectly realize the effect of optional protocols.

protocol TestProtocol {
    func test1()
}
extension TestProtocol {
    func test1() {
        print("TestProtocol test1")
    }
    func test2() {
        print("TestProtocol test2")
    }
}
class TestClass: TestProtocol {
    func test1() {
        print("TestClass test1")
    }
    func test2() {
        print("TestClass test2")
    }
}
var cls: TestProtocol = TestClass()
cls.test1() //TestClass test1
cls.test2() //TestProtocol test2

Generics

1. You can still use generic types from the original type in the extension.

2. Extend only if the conditions meet

extension Stack: Equatable where E: Equatable {
}

This is the end of this article about the detailed introduction to Swift Extension extension. For more related Swift Extension content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!