我第一次使用Swift 4中的Codable协议,我无法理解DecodabledecodeIfPresent的用法.

/// 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.

推荐答案

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

// 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"
}

但是not:

{
  "bar": "something"
}

而图表2将很乐意分析这两种情况.因此,在JSON个解析器的正常使用情况下,模型中的每个可选解析器都需要decodeIfPresent个.

Swift相关问答推荐

如何模拟可以立即返回和/或与Deliverc/await同步返回的CompletionButtons风格代码?

结束手势不会在滚动视图中触发

解码器是否需要具有密钥的外部数据表示?

如何使用Duration.TimeFormatStyle以h m s格式快速格式化时间

ToolbarItem 包含在动画中但不应该包含在动画中

SwiftUI 中的同一个 ForEach 中是否可以有 2 个数组?

有没有办法让文本字段以不同的 colored颜色 显示而不影响半透明背景?

标有@MainActor 的函数中的异步调用是否也在主线程上运行?

Swiftui 无法从核心数据中获取数据

如何判断一个值是否为 Int 类型

`let case(value)` 和 `case(let value)` 之间的区别 (Swift)

如何让 SwiftUI 中的文本在旋转框架的同时侧向显示?

为什么 Swift Tuples 只能在元素个数小于等于 6 的情况下进行比较?

如何使用 Date.ParseStrategy 在 Swift 5.6 中将字符串解析为日期?

在 Swift 中,如何查看 Process() 传递给 shell 的字符串?

找不到目标AAA的 SPM 工件 - 仅限 Xcode 13.3

在 Swift 中计算两个日期之间的差异

如何从 Button 获取标签名称?

Type 应该采用什么协议来让泛型函数将任何数字类型作为 Swift 中的参数?

如何在 Swift 中将 NSURL 转换为字符串