扩展中的Swift覆盖函数 [英] Swift override function in extension

查看:114
本文介绍了扩展中的Swift覆盖函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类:

 类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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆