3

I've seen this odd thing in the standard library for things like some operators for FloatingPoint (full source code).

protocol Foo: Bar {
    override static func baz()
}

I know that this is necessary when overriding some superclass' open method... but I've never needed to do this in a protocol, nor do I know what it means.

Ky -
  • 30,724
  • 51
  • 192
  • 308

1 Answers1

2

It means the protocol declares a new member that replaces an identical member in a parent protocol, though this isn't the same thing as "shadowing" (so it isn't exactly like C#'s new method-modifier keyword, also Swift supports static protocols, something C#s interface can't do).

In the link you gave for public protocol FloatingPoint, we see that FloatingPoint implements SignedNumeric.

FloatingPoint declares override mutating func negate() - but so does SignedNumeric - hence the need to add override.

The official Swift language 5.1 reference states this about the override keyword on classes (but not explicitly protocols), but the preface of the section implies that it applies to protocols insofar as it applies to all declarations:

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.

Dai
  • 141,631
  • 28
  • 261
  • 374
  • What's the usefulness of this? I thought simply declaring protocol inheritance also inherited the parent protocol's requirements – Ky - Aug 13 '21 at 04:30
  • 1
    @KyLeggiero (I'm not up-to-date on Swift, but I assume it's for future-proofing for when they do eventually support return-type-covariance (as of 2017, [it wasn't supported](https://stackoverflow.com/questions/42561685/why-cant-a-get-only-property-requirement-in-a-protocol-be-satisfied-by-a-proper)) - another reason is if you want to somehow extend the original protocol's declaration, such as adding `@attributes` - or updating the inline documentation. – Dai Aug 13 '21 at 04:53
  • Thank you! Those are really great reasons that make a lot of sense – Ky - Aug 13 '21 at 18:33