协议中的 override 是什么意思?
What does `override` mean in a protocol?
我在标准库中看到过这种奇怪的东西,比如 some operators for FloatingPoint
(full source code)。
protocol Foo: Bar {
override static func baz()
}
我知道在覆盖某些超类的 open 方法时这是必要的...但我从来不需要在协议中这样做,我也不知道这意味着什么。
这意味着协议声明了一个新成员来替换父协议中的相同成员,尽管这与 "shadowing" 不同(因此它与 C# 的 new
方法修饰符关键字,也 Swift 支持 static
协议,这是 C# interface
做不到的。
在您为 public protocol FloatingPoint
提供的 link 中,我们看到 FloatingPoint
实现了 SignedNumeric
。
FloatingPoint
声明 override mutating func negate()
- 但 SignedNumeric
也是如此 - 因此需要添加 override
.
官方 Swift 语言 5.1 参考说明了关于 类 上的 override
关键字(但不是明确的协议),但该部分的前言暗示它适用于协议只要它适用于 所有 声明:
https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID473
Methods that override a superclass method must be marked with the override
declaration modifier. It’s a compile-time error to override a method without the override
modifier or to use the override
modifier on a method that doesn’t override a superclass method.
我在标准库中看到过这种奇怪的东西,比如 some operators for FloatingPoint
(full source code)。
protocol Foo: Bar {
override static func baz()
}
我知道在覆盖某些超类的 open 方法时这是必要的...但我从来不需要在协议中这样做,我也不知道这意味着什么。
这意味着协议声明了一个新成员来替换父协议中的相同成员,尽管这与 "shadowing" 不同(因此它与 C# 的 new
方法修饰符关键字,也 Swift 支持 static
协议,这是 C# interface
做不到的。
在您为 public protocol FloatingPoint
提供的 link 中,我们看到 FloatingPoint
实现了 SignedNumeric
。
FloatingPoint
声明 override mutating func negate()
- 但 SignedNumeric
也是如此 - 因此需要添加 override
.
官方 Swift 语言 5.1 参考说明了关于 类 上的 override
关键字(但不是明确的协议),但该部分的前言暗示它适用于协议只要它适用于 所有 声明:
https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID473
Methods that override a superclass method must be marked with the
override
declaration modifier. It’s a compile-time error to override a method without theoverride
modifier or to use theoverride
modifier on a method that doesn’t override a superclass method.