Last active
December 17, 2018 05:58
-
-
Save magicien/615c3d19eed1b29a53f1612fd8fca315 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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