0

I'm consuming a JSON api that returns every field as a string. However some of those string values actually represent a timestamp and a longitude and latitude (as separate fields).

If I specify these values as a Date and Doubles respectively it swift throws an error Expected to decode Double but found a string

Struct Place {
    var created_at: Date?
    var longitude: Double?
    var latitude: Double?

}

I've seen some examples that seem to deal with Date formatting online, but I'm unsure what to do around the Double values?

I tried overriding init(from decoder:Decoder) but this still doesn't give the correct values:

e.g

init(from decoder:Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    longitude = try values.decode(Double.self, forKey: .longitude) //returns nil but using String works fine
}

I know I can extract the string and convert to a double like:

  longitude = Double(try values.decode(String.self, forKey: .longitude))

But is there another way?

Furthermore, I actually have a number of other properties that convert fine, but by doing this work around for these 3 properties, I now have to add all the other properties in there which seems a bit redundant. Is there a better way to do this?

1 Answer 1

1

If the JSON value is String you have to decode String. An implicit type conversion from String to Double is not possible.

You can avoid a custom initializer by adding a computed variable coordinate, in this case the CodingKeys are required

import CoreLocation

struct Place : Decodable {

    private enum CodingKeys: String, CodingKey { case createdAt = "created_at", longitude, latitude}

    let createdAt: Date
    let longitude: String
    let latitude: String

    var coordinate : CLLocationCoordinate2D {
        return CLLocationCoordinate2D(latitude: Double(latitude) ?? 0.0, longitude: Double(longitude) ?? 0.0)
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

It looks like I still need the custom init for the date unfortunately as that is also a string. But I like this computed property for the coordinate
You can add a date decoding strategy to decode the String to Date

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.