Swift 扩展计算变量在协议中声明之前无法正确读取

Swift Extension computed variable not read correctly until declared in protocol

我有一个声明和分配静态计算变量的协议扩展:

protocol DataType {
    
}
extension DataType {
    static var mocks: [Self] { [] }
}

然后我有另一个名为 Provider 的协议,它有一个 associatedtype DataType 协议的要求和一个扩展:

protocol Provider {
    associatedtype Data: DataType
}

extension Provider {
    static var mock: [Data] {
        Data.mocks
    }
}

然后我创建以下符合 DataType 和 Provider 的类型:

struct Car: DataType {
    var name: String
    
    static var mocks: [Car] {
        [.init(name: "Nissan"), .init(name: "Toyota")]
    }
}

struct CarProvider: Provider {
    typealias Data = Car
}

print(CarProvider.mock)

当我打印出来(空数组[])时,CarProvider静态变量mock打印出DataType的mocks变量的默认值-即使 Car 在其结构定义

中为 mocks 分配了数组值

但是,一旦我在 DataType 协议中声明 mocks 属性 作为要求,那么 Carmocks 值就是正确阅读(打印正确的值:[__lldb_expr_93.Car(name: "Nissan"), __lldb_expr_93.Car(name: "Toyota")]):

protocol DataType {
    static var mocks: [Self] { get }
}

为什么首先需要协议定义中的 属性 定义?扩展值不应该足够吗?由于 Car 结构将自己的值分配给 mocks 变量,难道不应该读取它而不是默认扩展值吗?

Why is the property definition required in the Protocol definition in the first place? Shouldn't the extension value be sufficient?

没有。协议扩展中的实现只能被认为是真正的默认实现,如果有某种方法可以在范围内覆盖它。没有协议中的要求,Swift 没有理由或机制来查看扩展之外的内容,因为在语义上没有其他匹配。

protocol DataType { }

extension DataType {
  static var mocks: [Self] { [] }
}

func mocks<Data: DataType>(_: Data.Type) -> [Data] {
  Data.mocks // This *is* the extension. That is the only truth.
}
protocol DataType {
  static var mocks: [Self] { get }
}

extension DataType {
  static var mocks: [Self] { [] }
}

func mocks<Data: DataType>(_: Data.Type) -> [Data] {
  Data.mocks // Now, we can dispatch to a concrete `Data` type!
}