[英]Overriding a method in an extension, Swift
Since which version of Swift does the following code no longer build?由于哪个版本的 Swift 不再构建以下代码?
import Foundation
@objc class Class: NSObject {
@objc func str() -> String {
return "Hello, playground"
}
}
class Subclass: Class {
}
extension Subclass {
override func str() -> String {
return "Hi"
}
}
From my understanding, previous versions of Swift compiled this code with unexpected results.根据我的理解,以前版本的 Swift 编译了这段代码,结果出乎意料。 On Swift 5.1, it no longer builds.在 Swift 5.1 上,它不再构建。
as you can see here ->Extensions documentation you can add new functionality but you can't override methods in extensions.正如您在此处看到的 ->扩展文档,您可以添加新功能,但不能覆盖扩展中的方法。
NOTE笔记
Extensions can add new functionality to a type, but they cannot override existing functionality.扩展可以向类型添加新功能,但它们不能覆盖现有功能。
So you can't do it in Swift 5.1所以你不能在 Swift 5.1 中做到
You can do it using the dynamic
modifier您可以使用dynamic
修饰符来做到这一点
@objc class Animal: NSObject {
@objc dynamic func saySomething() {
print("I am an Animal")
}
}
@objc class Dog: Animal { }
extension Dog {
override func saySomething() {
print("I am a Dog")
}
}
Dog().saySomething() // I am a Dog
Tested with Swift 5.1.3使用 Swift 5.1.3 测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.