Write a conditional conformance that makes Array Summable, and explain what it unlocks.
A Summable protocol requires one method, combined(with:), and Int already conforms. Make an Array of summable elements summable too.
Requirements:
- Add the conformance with a conditional
whereclause onElement. [Int]must gaincombined(with:), while[UIView]must not compile against it.- Delegate to each element's own
combined(with:)rather than reimplementing the math.
protocol Summable {
func combined(with other: Self) -> Self
}
extension Int: Summable {
func combined(with other: Int) -> Int { self + other }
}
// extend Array here
Write the conditional conformance.
A conditional conformance makes a generic type conform only when its parameter does — extension Array: Summable where Element: Summable. It unlocks the API for [Int] but not [UIView], as [T] becomes Equatable exactly when its T is.
- ✗Thinking the conformance applies to every element type unconditionally
- ✗Reimplementing element logic instead of delegating to the element's conformance
- ✗Believing a
whereclause on a function equals a conditional conformance
- →Why does
[UIView]fail to compile against the conformance? - →How does the standard library make
[T]Equatablethis way?
The conformance is gated on Element: Summable and delegates elementwise:
extension Array: Summable where Element: Summable {
func combined(with other: [Element]) -> [Element] {
zip(self, other).map { $0.combined(with: $1) }
}
}
Because the where Element: Summable clause gates it, [Int] gains combined(with:) for free while [UIView] never conforms and fails to compile against it. The body reuses each element's own combined(with:), so no new math is written. This is exactly how the standard library makes [T] conform to Equatable/Hashable only when T does.