0
0
Swiftprogramming~5 mins

Extensions with constraints in Swift

Choose your learning style9 modes available
Introduction
Extensions with constraints let you add new features to specific types only when they meet certain conditions. This helps keep your code organized and safe.
You want to add a function only to arrays that hold numbers.
You want to extend a protocol but only for types that conform to another protocol.
You want to add behavior to a generic type but only when the generic type meets a condition.
You want to keep your code clean by limiting extensions to certain types.
Syntax
Swift
extension TypeName where Condition {
    // new methods or properties
}
The where keyword sets the condition that the type must meet.
You can use constraints like Equatable, Comparable, or check if a type is a subclass.
Examples
Adds a sum() method only to arrays holding numbers.
Swift
extension Array where Element: Numeric {
    func sum() -> Element {
        return reduce(0, +)
    }
}
Adds a method to optionals whose wrapped type can be compared for equality.
Swift
extension Optional where Wrapped: Equatable {
    func isEqual(to value: Wrapped) -> Bool {
        return self == .some(value)
    }
}
Sample Program
This program adds a sum method only to arrays of numbers. It prints the sum of the numbers array. Trying to call sum on an array of strings would cause an error.
Swift
extension Array where Element: Numeric {
    func sum() -> Element {
        return reduce(0, +)
    }
}

let numbers = [1, 2, 3, 4, 5]
print("Sum of numbers:", numbers.sum())

let words = ["a", "b", "c"]
// words.sum() would not compile because String is not Numeric
OutputSuccess
Important Notes
Extensions with constraints help avoid errors by limiting where new code applies.
You cannot add stored properties in extensions, only computed properties and methods.
Use constraints to make your code more reusable and clear.
Summary
Extensions with constraints add features only to types that meet conditions.
Use the where keyword to set these conditions.
This keeps your code safe and organized.