Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. import Foundation
  2.  
  3. let json = """
  4. [
  5. { "name": "magicien" },
  6. { },
  7. { "name": "NoName" }
  8. ]
  9. """.data(using: .utf8)!
  10.  
  11. struct UserInfo: Codable {
  12. let _name: String?
  13. var name: String {
  14. get { return self._name ?? "NoName" }
  15. }
  16.  
  17. enum CodingKeys: String, CodingKey {
  18. case _name = "name"
  19. }
  20. }
  21.  
  22. let decoder = JSONDecoder()
  23. do {
  24. let users = try decoder.decode([UserInfo].self, from: json)
  25. for user in users {
  26. print("\(user.name) \(user._name)")
  27. }
  28. } catch DecodingError.keyNotFound(let key, let context) {
  29. print("keyNotFound: \(key): \(context)")
  30. } catch {
  31. print("\(error.localizedDescription)")
  32. }
  33.  
  34. /*
  35. magicien Optional("magicien")
  36. NoName nil
  37. NoName Optional("NoName")
  38. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement