我有一个协议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 C为finalie 的情况:
final class C : P {
func copy() -> C {
return C()
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想继承C,那么什么都行不通.有没有办法解决?
最近,我一直在使用Swift开发多个面向协议的应用程序框架,并注意到协议扩展中有一些(看似)奇怪的静态函数行为,特别是从元类型调用扩展函数的情况.
我最初发现这些行为的方式是对一个错误进行故障排除,其中一个对象的类型以一种看似不可能的方式发生了变化.我追查了问题并最终确定这是因为在静态函数中,Self并且self可能存在不同的类型(注意:我已经分别称这些为"Big S Self"和"Little s self").我将用我在游乐场中掀起的一些简单的例子来证明这一点:
class SomeBaseClass: SomeProtocol {}
class SomeChildClass: SomeBaseClass {}
protocol SomeProtocol {}
extension SomeProtocol {
static private func getName() -> String {
return "\(self): \(type(of: self))"
}
static func ambiguousName() -> String {
return getName()
}
static func littleName() -> String {
return self.getName()
}
static func bigName() -> String {
return Self.getName()
}
}
let child: SomeBaseClass.Type = SomeChildClass.self // SomeChildClass.Type
print(child.ambiguousName()) // "SomeChildClass: SomeBaseClass.Type\n"
print(child.littleName()) // "SomeChildClass: SomeBaseClass.Type\n"
print(child.bigName()) …Run Code Online (Sandbox Code Playgroud)