Skip to content

Instantly share code, notes, and snippets.

@magicien
Last active December 17, 2018 05:58
Show Gist options
  • Save magicien/615c3d19eed1b29a53f1612fd8fca315 to your computer and use it in GitHub Desktop.
Save magicien/615c3d19eed1b29a53f1612fd8fca315 to your computer and use it in GitHub Desktop.
import Foundation
let json = """
[
{ "name": "magicien" },
{ },
{ "name": "NoName" }
]
""".data(using: .utf8)!
struct UserInfo: Codable {
let _name: String?
var name: String {
get { return self._name ?? "NoName" }
}
enum CodingKeys: String, CodingKey {
case _name = "name"
}
}
let decoder = JSONDecoder()
do {
let users = try decoder.decode([UserInfo].self, from: json)
for user in users {
print("\(user.name), Default: \(user._name == nil)")
}
} catch DecodingError.keyNotFound(let key, let context) {
print("keyNotFound: \(key): \(context)")
} catch {
print("\(error.localizedDescription)")
}
/*
magicien, Default: false
NoName, Default: true
NoName, Default: false
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment