How to make a common class compatible with a protocol of a certain type?

Let's say there is a general structure:

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

Is it possible to expand the structure so that it conforms to the protocol for bounded T using where clauses? For instance. sort of

 extension Matrix where T: SpecificClass : SomeProtocol { // This does not compile :( } 
+5
source share
1 answer

No, such a construction is not possible (at least Swift 3.1).

For instance:

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

Gives a very clear error message:

A restricted Matrix type extension cannot have an inheritance clause.


But all is not lost ... as Alexander correctly noted, there is already a proposal built for Swift 4! This function will be called Conditional Compliance (SE-0143) .

A good example for all protocol-oriented programming of hackers:

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

If the array contains uniform elements, then the specified array is also equivalent.


Update . Swift 4 is missing, but this feature has not yet landed. We may have to wait until Swift 5 for this ...

+5
source

Source: https://habr.com/ru/post/1266995/


All Articles