I'm using latest version of Swift with xcode 10.1. I'm able to encode json from an object fine but decoding a json string back to an object is producing nil.
This is from a hacker noon tutorial and the tutorial source prints nil as well.
Here is the sample object:
class Car: NSObject, Codable {
var name: String = ""
var companyURL: URL? = nil
var yearOfManufacture: Int = 0
var isNew:Bool = true
var otherDetailsData: [String:String]? = nil
var carType: CarType = .Unknown
var carSize: CarSize = CarSize(height: 0, length: 0)
}
struct CarSize: Codable {
var height: Double
var length: Double
}
enum CarType: String, Codable {
case Unknown
case SUV
case Sedan
}
//here is sample json
let jsonString = """
{
"name":"City ZX",
"isNew":true,
"yearOfManufacture":2018,
"companyURL":"www.honda.com",
"carType":"Sedan",
"carSize":{
"height":200,
"height":100
},
"otherDetailsData":{
"color":"Red",
"fuelType":"Petrol"
},
}
"""
//here is where i attempt to create the object from the json string:
if let jsonData = jsonString.data(using: .utf8)
{
//And here you get the Car object back
let carTest = try? JSONDecoder().decode(Car.self, from: jsonData)
print("carObject currently printing nil ", carTest)
}
try?,catchthe error and print it. And a dictionary with twoheightkeys is invalid anyway.lengthin thecarSizedictionary?