UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Looking for an easy way to decode JSON into an object, but with partial data

Forums > Swift

One of the shortcomings of JSONDecoder is that it always creates a full object. For my use-case, this is not enough, because my API will send incremental changes, i.e. only the properties of an object that have been changed on server-side. So I am wondering how I can best handle this scenario with Swift.

In JavaScript, this would be pretty easy, using the spread operator, e.g.:

user = {

The only solution I have found for Swift this far is rather complex:


Is there any better / easier solution with the latest Swift versions?

(I also found SwiftyJSON. This actually resembles the way a JSON library for C# I was using implemented it. However, this approach requires to setup the model objects from the parsed JSON yourself. Also, the maintainers seem to have dropped the project.)


My first thought would be to do something like this:

Make an extension to the struct that represents a full JSON response but with optionals:

struct Person : Codable {
    var name: String?
    var height: Double?
    var weight: Double?
extension Person {

    mutating func merge(newData: Data) {
        let decoder = JSONDecoder()
        if let updatedPerson = try? decoder.decode(Person.self, newData) {
                self.name = updatedPerson.name ?? self.name
                self.height = updatedPerson.height ?? self.height

And then somewhere else:

func callAPI() {
     //some set up that gets a response
     Person.merge(newData: response)

Thoughts on this? I guess this is a bit complex too, though its the only way I can think of doing it.


Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.