Arm1.ru

Syntax sugar for JSON parsing in Swift

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

var myModel: MyModel?
do {
  myModel = try decoder.decode(MyModel.self, from: data)
} catch (let error) {
  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 just that:

let myModel = MyModel.decodeFromData(data: data)

And the same for encoding:

let data = MyModel.encode(fromEncodable: myModel)

All you need is just protocol conformance:

extension MyModel: Parseable {
  typealias ParseableType = Self
}

It's available on GitHub and might be used with Swift Package Manager: https://github.com/makoni/parsable

keyboard_return back