Advertisement
Larme

Untitled

Feb 9th, 2023
1,379
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.98 KB | None | 0 0
  1. func optionalKeyValueJSON() {
  2.  
  3.     let jsonStr1 = #"[{"key1":"value1", "key2": "value2"}]"#
  4.     let jsonStr2 = #"[{"key2": "value2"}]"#
  5.     let jsonStr3 = #"[{"key1": null, "key2": "value2"}]"#
  6.  
  7.     struct SCodable: Codable {
  8.         let key1: String?
  9.         let key2: String
  10.     }
  11.  
  12.     func decode(jsonStr: String) {
  13.         do {
  14.             let decoded = try JSONDecoder().decode([SCodable].self, from: Data(jsonStr.utf8))
  15.             print("Success: \(decoded)")
  16.         } catch {
  17.             print("Error: \(error)")
  18.         }
  19.     }
  20.  
  21.     decode(jsonStr: jsonStr1) //Works with key1 optional
  22.     decode(jsonStr: jsonStr2) //Works with key1 optional while key1 is not present in the JSON
  23.     decode(jsonStr: jsonStr3) //Works with key1 optional while key1 is null, ie ~ nil
  24. }
  25. optionalKeyValueJSON()
  26.  
  27. Outputs:
  28.  
  29. $>Success: [SCodable(key1: Optional("value1"), key2: "value2")]
  30. $>Success: [SCodable(key1: nil, key2: "value2")]
  31. $>Success: [SCodable(key1: nil, key2: "value2")]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement