I'm playing around with the new Codable
protocol in Swift 4. I'm pulling JSON data from a web API via URLSession
. Here's some sample data:
{
"image_id": 1,
"resolutions": ["1920x1200", "1920x1080"]
}
I'd like to decode this into structs like this:
struct Resolution: Codable {
let x: Int
let y: Int
}
struct Image: Codable {
let image_id: Int
let resolutions: Array<Resolution>
}
But I'm not sure how to convert the resolution strings in the raw data into separate Int
properties in the Resolution
struct. I've read the official documentation and one or two good tutorials, but these focus on cases where the data can be decoded directly, without any intermediate processing (whereas I need to split the string at the x
, convert the results to Int
s and assign them to Resolution.x
and .y
). This question also seems relevant, but the asker wanted to avoid manual decoding, whereas I'm open to that strategy (although I'm not sure how to go about it myself).
My decoding step would look like this:
let image = try JSONDecoder().decode(Image.self, from data)
Where data
is supplied by URLSession.shared.dataTask(with: URL, completionHandler: Data?, URLResponse?, Error?) -> Void)