Extending typed array by conforming to a protocol in Swift 2

后端 未结 3 1762
生来不讨喜
生来不讨喜 2021-01-13 04:48

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

3条回答
  •  独厮守ぢ
    2021-01-13 05:37

    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)

提交回复
热议问题