I want to extend a typed array Array
so that it conforms to a protocol SomeProtocol
. Now I know you can extend a typed array like b
You can't apply a lot of logic to conformance. It either does or does not conform. You can however apply a little bit of logic to extensions. The code below makes it easy to set specific implementations of conformance. Which is the important part.
This is used as a typed constraint later.
class SomeType { }
This is your protocol
protocol SomeProtocol {
func foo()
}
This is an extension of the protocol. The implementation of foo()
in an extension of SomeProtocol
creates a default.
extension SomeProtocol {
func foo() {
print("general")
}
}
Now Array
conforms to SomeProtocol
using the default implementation of foo()
. All arrays will now have foo()
as a method, which is not super elegant. But it doesn't do anything, so it's not hurting anyone.
extension Array : SomeProtocol {}
Now the cool stuff:
If we create an extension to Array
with a type constraint for Element
we can override the default implementation of foo()
extension Array where Element : SomeType {
func foo() {
print("specific")
}
}
Tests:
let arrayOfInt = [1,2,3]
arrayOfInt.foo() // prints "general"
let arrayOfSome = [SomeType()]
arrayOfSome.foo() // prints "specific"