使用Decodable进行JSON解析时,Optional和encodeIfPresent之间有什么区别? [英] What is difference between optional and decodeIfPresent when using Decodable for JSON Parsing?

查看:145
本文介绍了使用Decodable进行JSON解析时,Optional和encodeIfPresent之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用Swift 4中的 Codable 协议,我无法理解使用 decodeIfPresent 可销毁

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

/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
public func decodeIfPresent(_ type: String.Type, forKey key: KeyedDecodingContainer.Key) throws -> String?

此处提示返回 nil ,如果关联的键不包含值。如果这是唯一的原因,则它与可选属性有何不同,因为如果响应中不存在值,则可选变量还将设置为 nil

Here it suggest that it returns nil, if value not present with associated key. If this is the only reason , then how it differ from optional property, as optional variable also set to nil if value is not present in response.

推荐答案

这两行代码之间有一个细微但重要的区别:

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)

图1将解析:

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

不是

{
  "bar": "something"
}

而展览2将很高兴地解析两者。因此,在 JSON 解析器的正常使用情况下,您需要模型中每个可选内容的 decodeIfPresent

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.

这篇关于使用Decodable进行JSON解析时,Optional和encodeIfPresent之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆