这是我的游乐场:
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()
Swift有可能吗?我做错了什么?
更新
我真正想要的是这个(Playground与此代码崩溃):
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>()
答案 0 :(得分:1)
可能,你想要什么,不是你在做什么......请检查这个'示例'
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
*/
甚至更简单,因为那里根本不需要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()