【问题标题】:Why #Codable# not working in subclass which root class is confirmed to Codable protocol为什么#Codable# 不能在子类中工作,哪个根类已被 Codable 协议确认
【发布时间】:2018-03-12 15:20:04
【问题描述】:

[Xcode 9,Swift 4]

我测试以下代码:

为什么输出是-1,而不是1?

class A: Codable {

}

class A_a: A {
    var a: Int = -1
}

let json = """
{
"a": 1
}
"""
let jsonData = json.data(using: .utf8)!

let obj =  try? JSONDecoder().decode(A_a.self, from: jsonData)

obj?.a

【问题讨论】:

标签: swift4 codable


【解决方案1】:

Codable 是一个special 协议。它的使用受到严格监管。例如,您无法在扩展中确认它。 您只能依赖在其声明中确认为 Codable 的类型。

我认为,这是因为代码生成的工作原理。

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 2018-11-09
    • 2022-08-21
    • 2018-09-27
    • 2018-10-26
    • 2019-07-16
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多