Swift 3 extension constrained to a type

白昼怎懂夜的黑 提交于 2020-01-06 18:57:42

问题


I'd like to extend an RXSwift protocol, namely OsbervableConvertibleType, but I only want to create an extension method only on OsbervableConvertibleTypes, that has a Result object in them. Now, Result is generic again. But I'd like to retain the generic type in my extension function, so the return type of my function is generic as well. Something like this:

extension ObservableConvertibleType where E: Result<T> {
    public func asResultDriver() -> RxCocoa.SharedSequence<RxCocoa.DriverSharingStrategy, Result<T>> {
        return self.asObservable()
            .filter { $0.isSuccess }
            .map { $0.value! }
            .asDriver { _ in Driver.empty() }
    }
}

Is it possible in Swift 3?

Thanks!


回答1:


What you want to do is possible, but you will need to introduce an intermediate protocol, as Swift 3 does not support extension with generic type.

protocol ResultType {
  associatedtype Value

  var isSuccess: { Bool }
  var value: Value?
}

extension Result: ResultType { }

This gives you a base protocol ResultType, which you'll be able to use within the ObservableConvertibleType extension

extension ObservableConvertibleType where E: ResultType {
    public func asResultDriver() -> RxCocoa.SharedSequence<RxCocoa.DriverSharingStrategy, Result<E.Value>> {
        return self.asObservable()
            .filter { $0.isSuccess }
            .map { $0.value! }
            .asDriver { _ in Driver.empty() }
    }
}

If you want to read more, there are a lot of articles about this technique lying around google. The one that really helped me to understand it was this one.



来源:https://stackoverflow.com/questions/42507740/swift-3-extension-constrained-to-a-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!