小编典典

使用Decodable进行JSON解析时,Optional和DeleteIfPresent有什么区别?

swift

Codable第一次使用Swift 4的协议,我无法理解decodeIfPresentfrom的使用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如果响应中不存在值。


阅读 283

收藏
2020-07-07

共1个答案

小编典典

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

// 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模型中的每个可选项。

2020-07-07