相关疑难解决方法(0)

Protocol func返回Self

我有一个协议P,它返回一个对象的副本:

protocol P {
    func copy() -> Self
}
Run Code Online (Sandbox Code Playgroud)

以及实现P的C类:

class C : P {
    func copy() -> Self {
        return C()
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我是否输入返回值,因为Self我得到以下错误:

无法将类型为"C"的返回表达式转换为返回类型"Self"

我也试过回来了C.

class C : P {
    func copy() -> C  {
        return C()
    }
}
Run Code Online (Sandbox Code Playgroud)

这导致以下错误:

非终结类'C'中的方法'copy()'必须返回Self以符合协议'P'

没有什么可行的,除了我前缀class Cfinalie 的情况:

final class C : P {
    func copy() -> C  {
        return C()
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我想继承C,那么什么都行不通.有没有办法解决?

protocols subclassing swift swift-protocols

70
推荐指数
5
解决办法
2万
查看次数

标签 统计

protocols ×1

subclassing ×1

swift ×1

swift-protocols ×1