2016-01-29 119 views
1

這是我的遊樂場:斯威夫特嵌套泛型

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>() 
+1

我沒有問題,在編譯。也許你的代碼的其他部分會造成問題? – Sulthan

+0

@Sulthan你可以嘗試使用代碼中的任何類嗎? – gfpacheco

+0

完成。看到我的答案。 – Sulthan

回答

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 
*/ 

或者更簡單,因爲所需的初始化完全不存在需要..

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() 
+0

當我嘗試實例化'TypeAliasForGenericClassB'時,編譯器錯誤出現。嘗試這樣做:將'required'init(){}'添加到'B'和'BB',而不是使用TypeAliasForGenericClassB()更改'dump(TypeAliasForGenericClassB)'' – gfpacheco