How to make generic extension with associatedtype protocol in Swift
Issue #104
I like extensions, and I like to group them under 1 common property to easily access. This also makes it clear that these all belong to the same feature and not to confuse with Apple properties.
Grouping all related extensions
This is how I do it in Anchor and On
1 | activate( |
1 | textField.on.text { text in |
Generic extension
For On
, it is a bit tricky as it needs to adapt to different NSObject
subclasses. And to make auto completion work, meaning that each type of subclass gets its own function hint, we need to use generic and associatedtype
protocol.
You can take a look at Container and OnAware
1 | public class Container<Host: AnyObject>: NSObject { |
1 | public protocol OnAware: class { |
RxCocoa
RxSwift has its RxCocoa
that does this trick too, so that you can just declare
1 | button.rx.tap |
The power lies in the struct Reactive and ReactiveCompatible
protocol
1 | public struct Reactive<Base> { |
Here UIButton+Rx you can see how it can be applied to UIButton
1 | extension Reactive where Base: UIButton { |