Conditional Extensions in Swift

From the Swift cheat sheet · Extensions · verified Jul 2026

Conditional Extensions

Extensions with generic constraints

swift
// Extension with constraints
extension Array where Element: Numeric {
    func sum() -> Element {
        return reduce(0, +)
    }

    func average() -> Double {
        return isEmpty ? 0 : Double(sum() as! NSNumber) / Double(count)
    }
}

[1, 2, 3, 4, 5].sum()  // 15
[1.5, 2.5, 3.5].sum()  // 7.5

// Protocol extension with constraints
extension Collection where Element: Equatable {
    func allEqual() -> Bool {
        guard let first = first else { return true }
        return allSatisfy { $0 == first }
    }
}
💡 Generic where clauses enable powerful conditional extensions
⚡ Protocol extensions provide default implementations
📌 Conditional conformance adds protocol only when constraints are met
🟢 Use constraints to add methods only to specific generic types

More Swift tasks

Back to the full Swift cheat sheet