[英]Swift - Return subclass type in overridden function of superclass
I am trying to implement a Chainable object design in swift.我正在尝试在 swift 中实现可链接的 object 设计。 This is my structure:
这是我的结构:
class A{
func get() -> some A{
return self
}
}
class B:A{
func set(){
}
}
Can I create a method that would work even if I create a subclass of the original class?即使我创建了原始 class 的子类,我能否创建一个可以工作的方法? In my example, if I call
get
on B
I will get an object of type A
that does not have a method named set
.在我的示例中,如果我在
B
上调用get
,我将得到一个A
类型的 object ,它没有名为set
的方法。
let b = B()
b.get().set() // A has no member 'set'
So for this to work I would have to manually override every function in from A
in B
which is not the worst since I can call super but still wasting time and duplication of code.因此,要使其正常工作,我将不得不手动覆盖从
A
到B
中的每个 function,这并不是最糟糕的,因为我可以调用 super 但仍然浪费时间和重复代码。
If you don't really need to use an opaque type with the some
keyword, you can obtain what you want using protocols and extensions:如果你真的不需要使用带有
some
关键字的不透明类型,你可以使用协议和扩展来获得你想要的:
protocol Chainable {
func get() -> Self
}
extension Chainable {
func get() -> Self {
return self
}
}
class A: Chainable {}
class B: A {
func set() {
print("ok")
}
}
Now you get the desired return type for your get
function:现在您
get
了 function 所需的返回类型:
let a = A()
a.get() // Type = A
let b = B()
b.get() // Type = B
b.get().set() // Prints 'ok'
If you don't need to reuse this across multiple class hierarchies the solution can be even simpler (thanks to @Joakim Danielson for pointing this out):如果您不需要在多个 class 层次结构中重用它,则解决方案可以更简单(感谢@Joakim Danielson 指出这一点):
class A {
func get() -> Self {
return self
}
}
class B: A {
func set() {
print("ok")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.