Swift 中 class 怎么支持 Codable

之前翻译过 Mike Ash 的文章 Swift 4.0: Codable。 之后有读者DevHank 提了个问题:

image

迅速的在 Playgrounds 上面下写了一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Father: Codable {
var familyName: String = ""
}
class Son: Father {
var name: String = ""
}
let jsonText = """
{
"familyName": "F",
"name": "N"
}
"""
let data = jsonText.data(using: .utf8)!
do {
let son: Son = try JSONDecoder().decode(Son.self, from: data)
print(son.familyName)
} catch let error {
print(error)
}
// F

我以为事情就算结束了。后来实在是有些不妥, 然后在代码中添加

1
print(son.name)

发现出了问题。所以尝试让子类遵守 Codable 协议。 两个类的代码改成了这样

1
2
3
4
5
6
7
8
class Father {
var familyName: String = ""
}
class Son: Father, Codable {
var name: String = ""
}
// N

不难得出结论:简单的添加 Codable, 在继承中是无效的。在哪个类中遵守的 Codable, 其子类或者父类的成员都会被忽略。

再回到 Swift 4.0: Codable这篇文章中:有这么一句话

编译器会自动生成对应的 key 嵌套在 Person 类中。如果我们自己来做这件事情,这个嵌套类型会是这样的。

也就是说, 相关的 CodingKeyencode(to:)init(from:)方法都是编译器加上去的。这么看来这个问题就有解决方案了:自己实现 Codable 以及相关的实现。

这段话我在 WWDC (大概第28、9分钟)中,得到了苹果官方的证实。

所以又写了下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Father: Codable {
var familyName: String = ""
}
class Son: Father {
var name: String = ""
private enum CodingKeys: String, CodingKey {
case name = "name"
case familyName = "familyName"
}
// 如果要 JSON -> Son 必须实现这个方法
required init(from decoder: Decoder) throws {
super.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
familyName = try container.decode(String.self, forKey: .familyName)
}
// 如果要 Son -> JSON 必须实现这个方法
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(familyName, forKey: .familyName)
}
}
//N
//F

这段代码中, 父类遵守了 Codable 协议, 然后我在子类中自己实现了 CodingKey 相关的代码。最后的结果, 也是可喜的。

CepheusSun wechat
订阅我的公众号,每次更新我都不一定会告诉你!
坚持原创技术分享,您的支持将鼓励我继续创作!
0%