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

前端 未结 3 1594
执念已碎
执念已碎 2020-12-02 17:09

I am using Codable protocol from Swift 4 first time, I am not able to understand use of decodeIfPresent from Decodable.



        
3条回答
  •  余生分开走
    2020-12-02 17:46

    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.

提交回复
热议问题