Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Generic Constraints: Constrain the T of a generic item inside a generic sequence extension that is constrained to that generic type

Tags:

generics

swift

In Swift we can write extensions on generic items such as sequence:

extension Sequence where Iterator.Element : ObservableType {

}

This would guarantee the extension only applies to sequences of (in this case) RxSwift observables.

However if the element constraint is another generic can you then constrain that generic? e.g.:

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

 }

In the above pseudo code (that does not work) the intent is to say:

This extension should apply to sequences of Observable where the Observable is an Observable of type MyType e.g. [Observable]

like image 909
Cargowire Avatar asked Oct 30 '22 13:10

Cargowire


1 Answers

You can restrict Iterator.Element to types conforming to ObservableType and then add another constraint for the associated type E of Iterator.Element:

protocol ObservableType {
    associatedtype E
    // ...
}

class MyType { }

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

}
like image 132
Martin R Avatar answered Nov 24 '22 03:11

Martin R