我在标准库中看到了像 some 这样的奇怪东西operators for FloatingPoint
(full source code)。
protocol Foo: Bar {
override static func baz()
}
我知道在覆盖某些父类(super class)的 open 方法时这是必要的...但我从来不需要在协议(protocol)中这样做,我也不知道这意味着什么。
最佳答案
这意味着协议(protocol)声明了一个新成员来替换父协议(protocol)中的相同成员,尽管这与“阴影”不同(因此它与 C# 的 new
不完全相同)方法修饰符关键字,Swift 还支持 static
协议(protocol),这是 C#s interface
做不到的。
在您为 public protocol FloatingPoint
提供的链接中,我们看到 FloatingPoint
实现了 SignedNumeric
。
FloatingPoint
声明了 override mutating func negate()
- 但 SignedNumeric
也是如此 - 因此需要添加 override
.
官方 Swift 语言 5.1 引用说明了关于类上的 override
关键字(但没有明确说明协议(protocol)),但该部分的前言暗示它适用于协议(protocol),因为它适用于 所有声明:
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.
关于swift - `override` 在协议(protocol)中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57385250/