Swift 泛型延迟问题

6

我正在尝试做这件事情,但遇到了一些问题

这是自定义协议(CustomProtocol)

protocol CustomProtocol {

}

SubCustomProtocol

protocol SubCustomProtocol: CustomProtocol {

}

SubCustomProtocolImplementation

class SubCustomProtocolImplementation: SubCustomProtocol {

}

这是CustomClass。
class CustomClass<P: CustomProtocol> {

    var customProtocol: P?

    func doSomething() {

    } 

}

SubCustomClass

class SubCustomClass<P: SubCustomProtocol>: CustomSubClass {

}

And my BaseViewController

class BaseViewController<P: CustomProtocol, T: CustomClass<P>>: UIViewController {

    var foo: T!

    override func viewDidLoad() {
        super.viewDidLoad()
        foo?.doSomething()
    }
}

我的视图控制器

class ViewController<P: SubCustomProtocolImplementation, T: SubCustomClass<P>>: BaseViewController<P,T> {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

当我调用foo?.doSomething()时,它说“T不是CustomClass<'P'>的子类型”,我不知道自己做错了什么。

在ViewController声明中,它说“BaseViewController要求T继承自CustomClass<'P'>”。

希望我能帮到你!


我在 playground 中没有遇到这个错误。你确定你提供了完整的上下文吗? - iyuna
@Iyuna,我漏掉了一些东西,抱歉!我编辑了问题。 - Roberto Frontado
1
看起来,类型参数不能受到泛型类的约束。它可以受到类或协议的约束。 - CouchDeveloper
@CouchDeveloper 所以基本上我不能推迟泛型,对吗? - Roberto Frontado
似乎我们还不能这样做。Swift仍然不是一个完整的成熟语言。我建议提交一个功能请求。至少你可以像@lyuna所示那样解决它。 - CouchDeveloper
1个回答

2
如果你想将foo变量类型指定为CustomClass<P>,则应该按照以下方式进行。
class ViewController<P: CustomProtocol>: UIViewController {

    var foo: CustomClass<P>?

    override func viewDidLoad() {
        super.viewDidLoad()
        foo?.doSomething()
    }
}

谢谢,我知道,我没有解释清楚,我已经再次编辑了我的问题。 - Roberto Frontado

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接