Kenny Bambridge Kenny Bambridge -4 years ago 84
Swift Question

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 :(
}

Answer Source

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 {
   ...
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download