这是我的游乐场:

class A {

    required init() { // in order to use X() this init must be required
    }

}

class B<X: A> {

    required init() {
        X()
    }

}

class C<X: A, Y: B<X>> {

    init() {
        Y() // Error here: 'X' is not a subtype of 'A'
    }

}

C()

那有可能在斯威夫特吗?我做错什么了?
更新
我真正想要的是这个(这个代码会导致操场崩溃):
import UIKit
import CoreData

class MyEntity: NSManagedObject {}

class GenericCell<X: NSManagedObject>: UITableViewCell {

    func doSomething(entity: X) {}

}

class MyEntityCell: GenericCell<MyEntity> {}

class C<X: NSManagedObject, Y: GenericCell<X>>: UITableViewController {

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // here I should have Y = MyEntityCell
        tableView.registerClass(Y.self, forCellReuseIdentifier: "Cell")
    }

}

C<MyEntity, MyEntityCell>()

最佳答案

也许,你想要的,不是你在做什么。。。请检查这个“示例”

class A {
    required init() {
    }
}

class B<X: A> {
    required init() {
        //X()
    }

}
class BB: B<A>{
    required init() {
        //B()
    }
}

class C<SomeUnknownTypeAlias, TypeAliasForGenericClassB: B<SomeUnknownTypeAlias>> {

    init() {
    }
    func foo(){
        dump(TypeAliasForGenericClassB)
    }
}

let c = C()
dump(c)
c.foo()
let cc = C<A,BB>()
dump(cc)
cc.foo()
/*
- C<A, B<A>> #0
- B<A> #0
- C<A, BB> #0
- BB #0
*/

或者更简单,因为这里根本不需要required init。。
class A {}
class B<X: A> {}
class BB: B<A>{}

class C<SomeUnknownTypeAlias, TypeAliasForGenericClassB: B<SomeUnknownTypeAlias>> {

    init() {
    }
    func foo(){
        dump(TypeAliasForGenericClassB)
    }
}

let c = C()
dump(c)
c.foo()
let cc = C<A,BB>()
dump(cc)
cc.foo()

或者更通用,因为B没有X的要求
class A {}
class B<X>{}
class BB: B<A>{}

class C<SomeUnknownTypeAlias, TypeAliasForGenericClassB: B<SomeUnknownTypeAlias>> {

    init() {
    }
    func foo(){
        dump(TypeAliasForGenericClassB)
    }
}
// here C type requirements must be specified!
let c = C<A,B<A>>()
dump(c)
c.foo()
let cc = C<A,BB>()
dump(cc)
cc.foo()

关于swift - Swift嵌套泛型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35090468/

10-10 21:01