使用Swift 4嵌套的Codable协议

时间:2017-08-16 21:32:09

标签: swift4 xcode9 codable

我正在玩Swift 4和Codable一点点,并且遇到了一些嵌套协议的情况,这些协议都符合protocol CodableSomething: Codable {} protocol CodableAnotherThing: Codable { var something: CodableSomething { get } } struct Model: CodableAnotherThing { var something: CodableSomething }

简化示例如下所示:

Codable

This code正在使用Xcode 9 Beta 5构建错误:

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

现在,我没想到这些错误,因为我理解编译器会自动生成对这些协议的一致性,实际上,我甚至无法在没有构建错误的情况下手动实现此一致性。我还尝试了几种不同的方法来使用{{1}}来解决这种嵌套模型结构,但我无法使其工作。

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

1 个答案:

答案 0 :(得分:4)

如果您切换协议

  

CodableSomething

对于结构,您将没有错误,

进一步了解有关 Codable

的更多信息

可编码可以使用的类型是什么,为什么? 在那里,您基本上是对xCode讲这个

struct foo: Codable {
    var ok: Codable
}

那是不对的,请深入了解一下, CodableTypealias 您需要遵循以使用其子项,例如.Decode().Encode() 这些方法适用于值而不是抽象类型 因此将Codable类型赋予变量是不可能的。 因为Codabletypealias表示 DecodableEncodable

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

以及“可解码的”和“可编码的”都是确保这些值可编码和可解码的协议。

因此Codable是一种抽象,它无法解码或编码其自身类型的变量 但可以对已确认的类型进行编码和解码。