On Apple's take on how to handle JSON with Swift 3

A couple of days ago, Apple published this post in which they describe some ways one can parse JSON using core languages of Swift 3.

Weird thing, they suggest that it is OK to have a type download JSON by itself:

You can create a type method on the Restaurant structure that translates a query method parameter into a corresponding request object and sends the HTTP request to the web service. This code would also be responsible for handling the response, deserializing the JSON data, creating Restaurant objects from each of the extracted dictionaries in the “results” array, and asynchronously returning them in a completion handler.

Please don’t do this. Having a type inflate itself from the network is just a cry for trouble.

One thing I did like of Apple’s post is that they put all of their custom code on an extension of the type they’re trying to add JSON support to. What I didn’t like, though, is that they’re relying in initializers that decide wether the type can be inflated or not.

I really don’t like that.

For me, the correct approach is to have a type method that validates wether the JSON is valid or not, and then return a type instance from that:

extension Restaurant {
    static func with(json: [String:Any]) -> Restaurant? {
        // Verify that the JSON contains the correct values, etc.

You could either return nil there, or just throw a custom error with the key that’s missing, as they do in their example.

Swift is a language that pushes us to think functionally, and in terms of values. The static method on the type is the correct approach, I think. It also feels cleaner.

In case you want to read my full take on how I think JSON should be handled with Swift 3, you can read this post.

Esta entrada fue publicada en Swift y etiquetada , , . Enlace permanente.