Swift 协议扩展中变量的重新声明无效

Invalid Redeclaration of Variable in Swift Protocol Extension

在Swift中,据我了解,协议描述了可以应用于数据结构的属性。然后,协议扩展允许根据它们应用的数据结构定义这些属性。

如果是这样,为什么会出现以下错误:

invalid redeclaration of 'invalid'

这一行:

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

在此代码中:

struct Example: CausesError { }

protocol CausesError { var invalid: Bool { get } }

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

只是综合@dfri 对那些 see this later 实际错误是由以下原因引起的人所说的话:

extension CausesError where Self: Example

因为 Example 是一个结构,因此没有 Self 属性。

问题是我对协议扩展有一个根本性的误解。

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.

因此,我应该做的(为了在协议级别提供默认实现,甚至是数据类型)很简单:

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