What is difference between optional and decodeIfPresent when using Decodable for JSON Parsing?

There’s a subtle, but important difference between these two lines of code:

// Exhibit 1
foo = try container.decode(Int?.self, forKey: .foo)
// Exhibit 2
foo = try container.decodeIfPresent(Int.self, forKey: .foo)

Exhibit 1 will parse:

{
  "foo": null,
  "bar": "something"
}

but not:

{
  "bar": "something"
}

while exhibit 2 will happily parse both. So in normal use cases for JSON parsers you’ll want decodeIfPresent for every optional in your model.

Leave a Comment