如果我有一个类:
class Spaceship<FuelType> {
function prepareForLiftoff() throws {
//Start the countdown!
}
}
我最初假设我可以通过添加扩展来覆盖 prepareForLiftoff
而无需子类化:
extension Spaceship where FuelType: CollectionType {
func prepareForLiftoff() throws {}
}
虽然这段代码无法编译,但错误显示函数的无效重新声明
,这是有道理的。
我的问题是:有没有办法覆盖特定类的函数?换句话说,我可以在某些条件下替换功能,例如上面的示例,其中 FuelType: CollectionType
。如果没有,是否有任何其他解决方法或方法来实现该行为(可能声明另一个协议(protocol),idk)
现在我想得更多了,我不得不说这是不可能的,因为什么能阻止某人覆盖任何标准库函数?
最佳答案
来自documentation :
Extensions can add new functionality to a type, but they cannot override existing functionality.
文档仔细而准确地列出了允许扩展执行的操作。
关于你的问题:
Is there anyway to override a function of a particular class
是的,这叫做子类化。
关于ios - 扩展中的 Swift 覆盖功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33862414/