【问题标题】:Nested Codable protocols with Swift 4Swift 4 的嵌套 Codable 协议
【发布时间】:2018-01-25 04:09:51
【问题描述】:

我在玩 Swift 4 和 Codable 时遇到了一些场景,其中的嵌套协议都符合 Codable。

简化示例如下所示:

protocol CodableSomething: Codable {}

protocol CodableAnotherThing: Codable {
    var something: CodableSomething { get }
}

struct Model: CodableAnotherThing {
    var something: CodableSomething
}

This code 在 Xcode 9 Beta 5 中出现构建错误:

  • 类型“模型”不符合协议“可解码”
  • 类型“模型”不符合协议“可编码”

现在,我没想到会出现这些错误,因为我知道编译器会自动生成对这些协议的一致性,而事实上,如果没有构建错误,我什至无法手动实现这种一致性。我还尝试了几种不同的方法来使用Codable 来解决这种嵌套模型结构,但我就是无法让它工作。

我的问题:这是编译器错误(仍是测试版)还是我做错了什么?

【问题讨论】:

标签: swift4 xcode9 codable


【解决方案1】:

如果你切换协议

可编码的东西

对于一个结构,你不会有错误,

进一步了解可编码

Codable 可以处理哪些类型,为什么? 在那里你基本上是在对 xCode 说这个

struct foo: Codable {
    var ok: Codable
}

那是不对的,深入了解一下吧, Codable 是 Typealias 你需要遵守使用它的 subs 如 .Decode() , .Encode() 这些方法适用于值而不是抽象类型 所以给一个变量Codable 类型是行不通的。 因为Codable 是一个typealias,它表示 Decodable & Encodable

/// A type that can convert itself into and out of an external representation.
public typealias Codable = Decodable & Encodable

Decodable 和 Encodable 都是确保这些值是可编码和可解码的协议。

所以 Codable 是一种抽象,它不能解码或编码它自身类型的变量 但可以对已确认的类型进行编码和解码。

【讨论】:

  • 换句话说,Codable 不像(String、Int、Bool 等)数据类型,不是可以编码和解码的类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多