Search code examples
swiftgenericsswift4generic-programmingswift-protocols

How to make a generic class conform to a protocol for specific type?


Say there exists a generic struct:

public struct Matrix<T> where T: FloatingPoint, T: ExpressibleByFloatLiteral {
// some methods...
}

Is it possible extend the struct to conform to a protocol for constrained T using where clauses? E.g. something like

extension Matrix where T: SpecificClass : SomeProtocol {
    // This does not compile :(
}

Solution

  • No, such construct isn't possible (circa Swift 3.1 at least).

    For instance:

    class SomeClass { }
    protocol SomeProtocol { }
    
    extension Matrix: SomeProtocol where T == SomeClass { }
    

    Gives a very clear error message:

    Extension of type Matrix with constraints cannot have an inheritance clause.


    But all is not lost... as correctly noted by Alexander, there is already a proposal lined up for Swift 4! The feature will be called Conditional Conformances (SE-0143).

    A nice example for all protocol-oriented programming hackers out there:

    extension Array: Equatable where Element: Equatable {
       ...
    }
    

    If an array contains equatable elements than said array is also equatable.


    Update. Swift 4 is out but this feature hasn’t landed yet. We may need to wait until Swift 5 for this...