简体   繁体   English

通用参数受其他通用参数约束

[英]Generic parameter constrained by other generic parameter

Due to Swift's lack of covariance, I needed some workaround. 由于Swift缺乏协方差,我需要一些解决方法。 I'm coming from Java world, so I instinctively tried to create constraint from one type to other generic type. 我来自Java世界,因此我本能地尝试创建从一种类型到另一种通用类型的约束。

So I wrote the following class: 所以我写了下面的课:

class Factory<T: AnyObject> {
    let factoryClosure: () -> T

    init(closure: () -> T) {
        factoryClosure = closure
    }

    init<CHILD: T>(childFactory: Factory<CHILD>) {
        factoryClosure = { () -> T in
            return otherFactory.create()
        }
    }

    func create() -> T {
        return factoryClosure()
    }
}

I expected this to work just fine. 我希望这能正常工作。 I have the T defined and CHILD should be a subclass of T . 我定义了TCHILD应该是T的子类。 Swift compiler however disagrees and shows the following error on the line with init<CHILD: T> . 但是,Swift编译器不同意并在init<CHILD: T>的行上显示以下错误。

Inheritance from non-protocol, non-class type 'T' 从非协议,非类类型“ T”继承

I tried the generic parameter inheritance in different scenario as well. 我也在不同的场景中尝试了通用参数继承。 Adding the following method into the class (and removing the init that was causing the compile error). 在类中添加以下方法(并删除导致编译错误的init)。

func to<OTHER where OTHER: AnyObject, T: OTHER>() {

}

This yields basically the same output. 这产生基本上相同的输出。

Type 'T' constrained to non-protocol type 'OTHER' 类型“ T”限制为非协议类型“ OTHER”

Anything I though may work did not and ended with similar error message. 我虽然可能无法进行任何操作,但以类似的错误消息结束。 Is this a bug in Swift? 这是Swift中的错误吗? Or am I missing something? 还是我错过了什么? Or is it a feature of Swift and will never work as I thought? 还是它是Swift的功能,并且将永远无法按照我的想法工作?

If you want to pass any Factory<T> where T is of type AnyObject you just have to write: 如果要传递任何TAnyObject类型的Factory<T> ,则只需编写:

init(childFactory: Factory<T>) {
    factoryClosure = { () -> T in
        return otherFactory.create()
    }
}

because T is automatically constrained by your class. 因为T会自动受到您的班级的约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM