Invalid Redeclaration of Variable in Swift Protocol Extension

3k views Asked by At

In Swift, from what I understand, protocols describe attributes which can apply to a data structure. Protocol extensions then, allow for those attributes to be defined per data structure to which they apply.

If that is true, why does the following error appear:

invalid redeclaration of 'invalid'

On this line:

extension CausesError where Self: Example { var invalid: Bool { return true } }

In this code:

struct Example: CausesError { }

protocol CausesError { var invalid: Bool { get } }

extension CausesError where Self: Example { var invalid: Bool { return true } }
1

There are 1 answers

0
Brandon Bradley On BEST ANSWER

Just to synthesize what @dfri said for those who see this later The actual error was caused by:

extension CausesError where Self: Example

Because Example is a struct, and therefore has no Self property.

The problem was that I had a fundamental misconception about protocol extension.

A struct is concrete type, so defining a "default implementation" of invalid would simply corespond to conforming to the protocol. [One] could choose to let Example conform to CausesError by extension rather than at declaration:

extension Example: CausesError { var invalid: Bool { return true } }

but this is mostly semantics (w.r.t. direct conformance). This is not the same as supplying a default implementation (for a group of objects e.g. derived from a class type or conforming to some protocol), however, but simply conformance by a specific type to a given protocol.

Therefore, what I should have done (in order to provide default implementation at a protocol level, even to data types) was simply:

extension CausesError { var invalid: Bool { return false } }