swift - `override` 在协议(protocol)中是什么意思?

标签 swift overriding swift-protocols

我在标准库中看到了像 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 the override modifier or to use the override modifier on a method that doesn’t override a superclass method.

关于swift - `override` 在协议(protocol)中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57385250/

相关文章:

ios - 使用 swift 4 在 VIPER 中进行 dataTaskWithURL 崩溃单元测试

swift - 如何避免uitableview刷新

ios - swift - JSON 到 CoreData

ios - 错误原因 : unrecognized selector sent to instance after add library 'Google-Mobile-Ads-SDK' , '~> 7.8'

objective-c - objective-c 中的(覆盖)是什么

c++ - 用专门的版本覆盖多个继承的模板函数

c# - 是否可以在同一个类中覆盖一个函数?

ios - 使用扩展来扩展多个类

swift - 将数据从 CustomTableView 类发送到其父 View Controller

转义反斜杠时 Swift 中的正则表达式不起作用