Extending typed array by conforming to a protocol in Swift 2

后端 未结 3 1767
生来不讨喜
生来不讨喜 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:28

    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"
    

提交回复
热议问题