Arm1.ru

Syntax sugar for JSON parsing in Swift

JSON decoding and encoding became easy after adding Codable protocol in Swift 4.0. But during coding I wanted to have something shorter and more elegant than Do-Catch statement that looks like this:

var myModel: MyModel?
let decoder = JSONDecoder()

do {
    myModel = try decoder.decode(MyModel.self, from: data)
} catch {
    print(error.localizedDescription)
}

Or like this:

let myModel: MyModel? = try? decoder.decode(MyModel.self, from: data)

So I wrote a protocol with default implementation that allows to do decoding just like that:

let myModel = MyModel.decodeFromData(data: data)

And the same for encoding:

let data = MyModel.encode(fromEncodable: myModel)

All you need is just to add protocol conformance:

extension MyModel: Parseable {
    typealias ParseableType = Self
}

It's available on GitHub as a Swift Package: https://github.com/makoni/parsable

keyboard_return back