-
-
Save slimlime/0c289ac2cc7e76d98d4a8091372835d3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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