Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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) \(user._name)")
- }
- } catch DecodingError.keyNotFound(let key, let context) {
- print("keyNotFound: \(key): \(context)")
- } catch {
- print("\(error.localizedDescription)")
- }
- /*
- magicien Optional("magicien")
- NoName nil
- NoName Optional("NoName")
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement