tad*_*ija 7 swift4 xcode9 codable
我正在使用Swift 4和Codable一点点,并且遇到了一些具有嵌套协议的场景,这些协议都符合Codable.
简化示例如下所示:
protocol CodableSomething: Codable {}
protocol CodableAnotherThing: Codable {
var something: CodableSomething { get }
}
struct Model: CodableAnotherThing {
var something: CodableSomething
}
Run Code Online (Sandbox Code Playgroud)
此代码使用Xcode 9 Beta 5进行构建错误:
现在,我没想到这些错误,因为我理解编译器会自动生成对这些协议的一致性,实际上,我甚至无法在没有构建错误的情况下手动实现此一致性.我也尝试了几种不同的方法来解决这种嵌套模型结构的使用,Codable但我无法使其工作.
我的问题:这是一个编译器错误(它仍然是测试版)或者我做错了什么?
如果你切换协议
可编码的东西
对于一个结构,你不会有错误,
更进一步并阅读有关 Codable 的更多信息
Codable可以处理哪些类型以及为什么?在那里你基本上是在对 xCode 说这个
struct foo: Codable {
var ok: Codable
}
Run Code Online (Sandbox Code Playgroud)
深入研究它是不对的,
您Codable需要Typealias
遵守才能使用其子项,例如.Decode(),.Encode()
这些方法适用于值而不是抽象类型,因此Codable为变量提供类型是行不通的。因为Codable是 atypealias表示
Decodable&Encodable
/// A type that can convert itself into and out of an external representation.
public typealias Codable = Decodable & Encodable
Run Code Online (Sandbox Code Playgroud)
Decodable 和 Encodable 都是确保这些值可编码和可解码的协议。
所以 Codable 是一个抽象,它不能解码或编码其自身类型的变量,但可以编码和解码已确认的类型。
| 归档时间: |
|
| 查看次数: |
1785 次 |
| 最近记录: |