扩展中的Swift覆盖函数 [英] Swift override function in extension
问题描述
如果我有一个类:
类Spaceship< FuelType> {
的功能,这是有道理的。
函数prepareForLiftoff()抛出{
//开始倒计时!
$ b我原本以为我可以覆盖prepareForLiftoff
无需通过添加扩展来创建子类:
扩展Spaceship其中FuelType:CollectionType {
func prepareForLiftoff()throws {}
}
这段代码没有' t编译虽然,错误说
无效重新声明
我的问题是:是否有重写某个特定类的函数?换句话说,我可以在某些情况下替换功能,例如上面的示例
FuelType:CollectionType
。如果没有,是否有任何其他的解决方法或方法来实现该行为(也许宣布另一个协议,idk)
现在我想到更多,我不得不说这是不可能的,因为什么是阻止某人重写任何标准库函数? 解析方案
从文档:
扩展可以为类型添加新功能,但不能覆盖现有功能。
准确地说是什么扩展是允许做。
至于你的问题:
是否有重写某个类的函数
是的,它叫做子类。
If I have a class:
class Spaceship<FuelType> {
function prepareForLiftoff() throws {
//Start the countdown!
}
}
I originally assumed that I would be able to override prepareForLiftoff
without subclassing by adding an extension:
extension Spaceship where FuelType: CollectionType {
func prepareForLiftoff() throws {}
}
This code doesn't compile though, the error says invalid redeclaration
of the function, which makes sense.
My question is: Is there anyway to override a function of a particular class? In other words can I replace the functionality under certain conditions like the example above where FuelType: CollectionType
. If not, is there any other workaround or way to achieve that behavior (maybe declaring another protocol, idk)
Now that I think about it more, I would have to say that's not possible because what's to stop someone from overriding any of the standard library functions?
From the documentation:
Extensions can add new functionality to a type, but they cannot override existing functionality.
The documentation lists carefully and precisely what an extension is allowed to do.
As to your question:
Is there anyway to override a function of a particular class
Yes, it's called subclassing.
这篇关于扩展中的Swift覆盖函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!