简体   繁体   中英

Generic parameter constrained by other generic parameter

Due to Swift's lack of covariance, I needed some workaround. I'm coming from Java world, so I instinctively tried to create constraint from one type to other generic type.

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 . Swift compiler however disagrees and shows the following error on the line with init<CHILD: T> .

Inheritance from non-protocol, non-class type '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).

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

}

This yields basically the same output.

Type 'T' constrained to non-protocol type 'OTHER'

Anything I though may work did not and ended with similar error message. Is this a bug in Swift? Or am I missing something? Or is it a feature of Swift and will never work as I thought?

If you want to pass any Factory<T> where T is of type AnyObject you just have to write:

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

because T is automatically constrained by your class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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