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
In more recent versions of Swift it is possible to write:
extension Array: SomeProtocol where Element == SomeType { ... }
Unsure in which version of Swift this became possible, but the following works in Swift 4.1
class SomeType { }
protocol SomeProtocol {
func foo()
}
extension Array: SomeProtocol where Element == SomeType {
func foo() {
print("foo")
}
}
let arrayOfSome = [SomeType()]
arrayOfSome.foo() // prints "foo"
let arrayOfInt = [1,2,3]
arrayOfInt.foo() // Will not compile: '[Int]' is not convertible to 'Array'
(I am aware that the question specifically asks for Swift 2, but I am adding this for reference)