Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. /*
  2. Paste this in a Swift Playground
  3. */
  4.  
  5. import Foundation
  6. import CoreLocation
  7.  
  8. var json = """
  9. {
  10. "name" : "Test",
  11. "latitude" : 39.9638412115116,
  12. "longitude" : 4.27464941734696
  13. }
  14. """.data(using: .utf8)!
  15.  
  16. struct MyLocation: Codable {
  17. let name: String
  18. let latitude: Double
  19. let longitude: Double
  20. let location: CLLocationCoordinate2D
  21.  
  22. enum CodingKeys: String, CodingKey {
  23. case name
  24. case latitude
  25. case longitude
  26. }
  27.  
  28. public init(from decoder: Decoder) throws {
  29. let container = try decoder.container(keyedBy: CodingKeys.self)
  30. name = try container.decode(String.self, forKey: .name)
  31. latitude = try container.decode(Double.self, forKey: .latitude)
  32. longitude = try container.decode(Double.self, forKey: .longitude)
  33. location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
  34. }
  35.  
  36. func encode(to encoder: Encoder) throws {
  37. var container = encoder.container(keyedBy: CodingKeys.self)
  38. try container.encode(name, forKey: .name)
  39. try container.encode(latitude, forKey: .latitude)
  40. try container.encode(longitude, forKey: .longitude)
  41. }
  42. }
  43.  
  44. let myLocation = try JSONDecoder().decode(MyLocation.self, from: json)
  45. print(myLocation)
  46.  
  47. let encodedMyLocation = try JSONEncoder().encode(myLocation)
  48. print(encodedMyLocation)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement