where clauses on extensions
Use where on type and protocol extensions to add APIs only when constraints hold (e.g., Array where Element: Equatable , Collection where Element == Int ).
Why constrained extensions?
Add APIs only when types meet constraints using where on extensions:
- Type extensions (e.g.,
Array) - Protocol extensions (e.g.,
Collection) - Exact-match constraints (e.g.,
Element == Int)
Type extension with constraint
Attach methods to Array only when its Element is Equatable. Non-Equatable arrays won’t see these APIs.
extension Array where Element: Equatable {
func removing(_ value: Element) -> [Element] {
filter { $0 != value }
}
func containsAll(_ others: [Element]) -> Bool {
others.allSatisfy(self.contains)
}
}
print([1,2,3].removing(2)) // [1,3]
print(["a","b"].containsAll(["b"])) // trueAll lessons in this course
- Conditional conformances
- Recursive constraints & higher-order generics
- where clauses on extensions