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.swift150 chars5 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.swift315 chars15 lines
This function is generic and reusable, allowing us to parse JSON into any Codable
type with a single function call.
gistlibby LogSnag