Nested general constraints: restrict T of a common element within a common extension of a sequence that is limited to this common type

In Swift, we can write extensions for common elements, such as a sequence:

extension Sequence where Iterator.Element : ObservableType { } 

This ensures that the extension only extends to the sequences (in this case) of the observed RxSwift.

However, if an element restriction is another general, can you limit this general? eg:.

 extension Sequence where Iterator.Element : ObservableType where E : MyType { } 

In the above pseudo code (which does not work), the intention is to say:

This extension should apply to Observable sequences, where Observable is an observable of type MyType, for example. [Observed]

+5
source share
1 answer

You can restrict Iterator.Element type corresponding to ObservableType , and then add another constraint to the associated E type of Iterator.Element :

 protocol ObservableType { associatedtype E // ... } class MyType { } extension Sequence where Iterator.Element: ObservableType, Iterator.Element.E: MyType { } 
+2
source

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


All Articles