generic codable parsing in swift

To achieve generic codable parsing in Swift, we can define a generic function that takes a JSON input as Data and the target type as a T.Type.

main.swift
func parse<T: Codable>(_ data: Data, as type: T.Type) throws -> T {
    let decoder = JSONDecoder()
    return try decoder.decode(type, from: data)
}
150 chars
5 lines

This function takes advantage of the Codable protocol in Swift, which makes encoding and decoding with JSON easy. We create an instance of JSONDecoder, which has sensible defaults for decoding JSON, and then use that to decode the input JSON into an instance of the target type. If any errors occur during decoding, they are thrown as errors.

We can call this function with any type that conforms to Codable. For example, to parse a JSON array into an array of Person structs:

main.swift
struct Person: Codable {
    let name: String
    let age: Int
}

let json = """
[
    { "name": "Alice", "age": 30 },
    { "name": "Bob", "age": 25 }
]
""".data(using: .utf8)!

let people = try parse(json, as: [Person].self)
print(people) // prints: [Person(name: "Alice", age: 30), Person(name: "Bob", age: 25)]
315 chars
15 lines

This function is generic and reusable, allowing us to parse JSON into any Codable type with a single function call.

gistlibby LogSnag