1

[Xcode 9, Swift 4]

I test following code:

Why the output is -1, not 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
ZYiOS
  • 5,204
  • 3
  • 39
  • 45
  • Possible duplicate of [How do I use custom keys with Swift 4's Decodable protocol?](https://stackoverflow.com/questions/44396500/how-do-i-use-custom-keys-with-swift-4s-decodable-protocol) – Tamás Sengel Oct 03 '17 at 12:46
  • @the4kman this is not the duplicate of the question you mentioned. – PGDev Oct 05 '17 at 09:52
  • Finally, I got the answer here: [https://stackoverflow.com/questions/44553934/using-decodable-in-swift-4-with-inheritance](https://stackoverflow.com/questions/44553934/using-decodable-in-swift-4-with-inheritance). @PGDev – ZYiOS Oct 26 '17 at 07:15

1 Answers1

0

Codable is a special protocol. Its use is highly regulated. For example you cannot confirm to it in an extension. You can only rely on Types that confirm to Codable in their declaration.

I think, it is because how code-generation works.