Type Extensions in Swift

From the Swift cheat sheet · Extensions · verified Jul 2026

Type Extensions

Adding functionality to existing types

swift
// Extending existing types
extension Int {
    var isEven: Bool {
        return self % 2 == 0
    }

    func squared() -> Int {
        return self * self
    }
}

let number = 42
print(number.isEven)  // true
print(number.squared())  // 1764

// Extending with initializers
extension String {
    init(banner str: String, times count: Int) {
        self = String(repeating: str, count: count)
    }
}
💡 Extensions can add computed properties but not stored properties
⚡ Use extensions to organize code into logical groups
📌 Extensions can add protocol conformance retroactively
🟢 Extensions work on all types: classes, structs, enums, protocols

More Swift tasks

Back to the full Swift cheat sheet