问题
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