【问题标题】:Swift Compilation Error for Property Wrappers with Codable in multiple files多个文件中带有 Codable 的属性包装器的 Swift 编译错误
【发布时间】:2019-10-28 03:07:39
【问题描述】:

在多个文件中可编码的属性包装器编译失败。

我在下面的 Swift 源代码中找到了测试代码:

@propertyWrapper
struct Printed<Value: Codable>: Codable {
    var wrappedValue: Value {
        didSet { print(wrappedValue) }
    }
}

struct Foo: Codable {
    @Printed var bar: Bool = false
}
func test(_ value: Foo = Foo()) {
  let _: Codable = value
}

并在我的测试项目中使用它们:

TestProject

但是编译失败并出现错误:

Type 'Foo' does not conform to protocol 'Encodable'

如何解决?

【问题讨论】:

    标签: swift codable property-wrapper


    【解决方案1】:

    这是一个可见性问题...最简单的解决方法是将这些辅助结构移动到 ViewController 模块中,如下所示...运行,一切正常(使用 Xcode 11.2 测试)

    【讨论】:

      【解决方案2】:

      测试 Foo 结构不必是可编码的。

      测试在 bar 属性上。并且 Bool 类型已经适应 Codable。

      struct Foo{
          @Printed var bar: Bool = false
      }
      
      func test(_ value: Foo = Foo()) {
         var m = value
         m.bar = true. // will call didSet in @printed struct
      }
      

      【讨论】:

      • 感谢您的回答。我想使用可编码的属性包装器,它应该是一个简单的能力。而且我在github的swift source中找到了测试代码,但是编译不出来。
      • 在继续之前,您需要了解协议的定义。
      【解决方案3】:

      允许test 接受通用Codable,如果这是该功能的唯一要求:

      func test<T: Codable>(_ value: T) {
          let val = value
      }
      

      【讨论】:

        猜你喜欢
        • 2021-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-23
        • 2015-07-21
        • 1970-01-01
        相关资源
        最近更新 更多