szantogab
szantogab

Reputation: 45

Swift 3 extension constrained to a type

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!

Upvotes: 0

Views: 476

Answers (1)

tomahh
tomahh

Reputation: 13661

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.

Upvotes: 2

Related Questions