Swift 3扩展限制为一个类型 [英] Swift 3 extension constrained to a type

查看:261
本文介绍了Swift 3扩展限制为一个类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扩展一个RXSwift协议,即OsbervableConvertibleType,但是我只想仅在OsbervableConvertibleTypes上创建一个扩展方法,该方法中包含一个Result对象.现在,结果再次是通用的.但是我想在扩展函数中保留泛型类型,因此函数的返回类型也是泛型的.像这样:

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() }
    }
}

在Swift 3中有可能吗?

Is it possible in Swift 3?

谢谢!

推荐答案

您可能想要做的事,但是您将需要引入一个中间协议,因为Swift 3不支持泛型类型的扩展.

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 { }

这为您提供了基本协议ResultType,您可以在ObservableConvertibleType扩展名内使用该协议

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.

这篇关于Swift 3扩展限制为一个类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆