如何实现返回协变Selfs的协议方法? [英] How do you implement protocol methods that return covariant Selfs?

查看:63
本文介绍了如何实现返回协变Selfs的协议方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误:协议'协议'要求'实例'不能被非最终类('Class')满足,因为它在非参数非结果类型位置使用'Self'

protocol Protocol {
    var instance: Self {get}
}

class Class: Protocol {
    var instance: Class {return Subclass()}
}

class Subclass: Class {}

以下是我在C#中表达我想要的内容。 (据我所知,C#没有办法强制执行泛型参数Self实际上是我们从Swift知道的Self,但它的功能很好,因为文档应该让我做正确的事。)

Here is how I would express what I want, in C#. (C# does not, to my knowledge, have a way to enforce that the generic parameter "Self" is actually the Self we know from Swift, but it functions well enough as documentation that should make me do the right thing.)

interface Protocol<Self> where Self: Protocol<Self> {
    Self instance {get;}
}

class Class: Protocol<Class> {
    public Class instance {get {return new Subclass();}}
}

class Subclass: Class {}

......在未来版本的Swift中看起来如何:

protocol Protocol {
    typealias FinalSelf: Protocol where FinalSelf.FinalSelf == FinalSelf

    var instance: FinalSelf {get}
}

class Class: Protocol {
    var instance: Class {return Subclass()}
}

class Subclass: Class {}

我如何模仿与我的问题相关的部分:

protocol Protocol: ProtocolInstance {
    static var instance: ProtocolInstance {get}
}

protocol ProtocolInstance {}


class Class: Protocol {
    static var instance: ProtocolInstance {return Subclass()}
}

class Subclass: Class {}

而且,这就是我所相信的成为我的代码的相关部分:

And, here is what I believe to be the relevant portion of my code:

这篇关于如何实现返回协变Selfs的协议方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆