Created
January 26, 2018 22:36
-
-
Save dmiedema/1d022fd5e0846ea740192fc16587ae54 to your computer and use it in GitHub Desktop.
Swift Codable is a little weird...
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 | |
// 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