Swift4的Codable协议非常有用。如果正确定义了一致性,它将提供默认的实现函数。
例如,这完全没问题:
struct Good: Codable {
var foo: String // Non-optional
var bar: Int? // Optional
}但这将引发编译错误,并请求创建符合协议的
struct Bad: Codable {
var foo: UIButton // Non-optional raise compile error for not conforming Codable Protocol
var bar: UIView? // optional is okay (not compile error because when decode failed, it fallback to nil)
var codable: SomeCodable // if the property is also Codable, then it's fine too!
}因此,问题是:我是否可以编写一个协议,要求其符合自身(就像属性需要符合同一协议一样)?
如果是,是如何实现的?若否,原因何在?
另外,我还想知道在结构中定义CodingKeys会如何改变编码/解码行为?我可以在我的协议中做类似的事情吗?
发布于 2019-05-07 19:12:33
Martin是正确的,你不能在不接触编译器的情况下自己做这件事。
首先,让我们看一下这个基本的示例,其中我解释了如何使用编码键。
struct CodableStruct: Codable {
let primitive: Int // No issues yet
enum CodingKeys: String, CodingKey {
case primitive
// This is the default coding key (i.e the JSON has structure ["primitive": 37]
// You can change this key to anything you need
//
// ex case primitive = "any_thing_you_want"
// JSON has to have structure ["any_thing_you_want": 37]
}}
更改codingKey只会更改代码在从JSON中“解码”该值时将使用的键。
现在让我们来谈谈编译器。假设我们创建另一个struct
struct NotCodableStruct {
let number: Double
}此结构不符合Codable。如果我们把这段代码添加到前面的结构中,我们会得到:
struct CodableStruct: Codable {
let primative: Int
let notCodable: NotCodableStruct // doesn't compile because this doesn't conform to codable
enum CodingKeys: String, CodingKey {
case primative
case notCodable
}
}由于NotCodableStruct不符合Codable,编译器抱怨道。换句话说,符合Codable的结构或对象中的所有变量也必须符合Codable。有关更多信息,请参见以下屏幕截图。

当然,如果您让NotCodableStruct符合Codable,每个人都会再次高兴起来。由于您无法强制要求所有变量都符合Codable,因此您无法制定类似的协议。
https://stackoverflow.com/questions/56017574
复制相似问题