Created
August 22, 2017 10:31
-
-
Save magicien/de3268a68dca3993bfff5de6ac61e69e 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 = """ | |
{ | |
"user_id": 1, | |
"user_name": "magicien", | |
"friends": [ | |
{ | |
"user_id": 2, | |
"is_best_friend": true | |
} | |
] | |
} | |
""".data(using: .utf8)! | |
struct UserInfo: Codable { | |
let uid: Int | |
var numOfBestFriends: Int | |
enum CodingKeys: String, CodingKey { | |
case uid = "user_id" | |
case userName = "user_name" | |
case friends | |
} | |
enum FriendKeys: String, CodingKey { | |
case uid = "user_id" | |
case isBestFriend = "is_best_friend" | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
self.uid = try container.decode(Int.self, forKey: .uid) | |
self.numOfBestFriends = 0 | |
var friendsContainer = try container.nestedUnkeyedContainer(forKey: .friends) | |
while !friendsContainer.isAtEnd { | |
let friendContainer = try friendsContainer.nestedContainer(keyedBy: FriendKeys.self) | |
let isBestFriend = try friendContainer.decode(Bool.self, forKey: .isBestFriend) | |
if isBestFriend { | |
self.numOfBestFriends += 1 | |
} | |
} | |
} | |
func encode(to encoder: Encoder) throws { | |
// do something | |
} | |
} | |
let decoder = JSONDecoder() | |
do { | |
let userInfo = try decoder.decode(UserInfo.self, from: json) | |
print(userInfo.numOfBestFriends) | |
} catch DecodingError.keyNotFound(let key, let context) { | |
print("keyNotFound: \(key): \(context)") | |
} catch { | |
print("\(error.localizedDescription)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment