Skip to content

Instantly share code, notes, and snippets.

@dmiedema
Created January 26, 2018 22:36
Show Gist options
  • Save dmiedema/1d022fd5e0846ea740192fc16587ae54 to your computer and use it in GitHub Desktop.
Save dmiedema/1d022fd5e0846ea740192fc16587ae54 to your computer and use it in GitHub Desktop.
Swift Codable is a little weird...
import Foundation
// When using swift codable to parse JSON into a struct
let json = [
"non_accessible": true,
"index": 7
] as [String : Any]
struct Info: Codable {
let index: Int
var isPreferred: Bool? = false
var nonAccessible: Bool? = false
enum CodingKeys: String, CodingKey {
case index
case isPreferred = "is_preferred"
case nonAccessible = "non_accessible"
}
}
let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let jsonDecoder = JSONDecoder.init()
let info = try! jsonDecoder.decode(Info.self, from: data)
// What's the value of `info.isPreferred`? `false`, or `nil`?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment