【问题标题】:Swift nested genericsSwift 嵌套泛型
【发布时间】:2016-01-30 05:42:49
【问题描述】:

这是我的游乐场:

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

【问题讨论】:

  • 我编译它没有问题。也许您的代码的其他部分出现问题?
  • @Sulthan 你可以尝试使用代码中的任何类吗?
  • 完成。看我的回答。
  • @Sulthan 我完全重写了我的操场。当我尝试创建 Y 实例时发生错误,您知道出了什么问题吗?
  • 添加了关联类型的解决方案。您还应该将编译器崩溃报告为错误。代码不应该工作,但编译器在尝试编译时不应该崩溃:)

标签: swift generics


【解决方案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()

【讨论】:

  • 当我尝试实例化TypeAliasForGenericClassB 时出现编译器错误。尝试这样做:将required init() {} 添加到BBB,而不是将dump(TypeAliasForGenericClassB) 更改为TypeAliasForGenericClassB()
猜你喜欢
  • 1970-01-01
  • 2016-07-27
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 2014-06-03
  • 1970-01-01
相关资源
最近更新 更多