swift - 使用 Swift JSONEncoder 编码时会发生什么错误

标签 swift codable

JSONEncoder方法 func encode<T>(_ value: T) throws -> Data where T : Encodable是可抛出的。

我想知道为什么它是可抛出的:如果要编码的值不符合 Encodable ,它无法通过编译器检查,因此在运行时应该不会遇到任何错误。

最佳答案

来自 JSONEncodersource code :

/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.


所有错误的调试说明:

Top-level (T.self) did not encode any values.

Top-level (T.self) encoded as null JSON fragment.

Top-level (T.self) encoded as number JSON fragment.

Top-level (T.self) encoded as string JSON fragment.

关于swift - 使用 Swift JSONEncoder 编码时会发生什么错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45365671/

相关文章:

json - 在 Codable - Swift 中使用 "/"和 "%"

json - 如何确保所有 JSON 字段都呈现在 Swift Decodable 模型中?

ios - 如何从子数组对象中检索属性值?

swift - 对于包含一些简单配置参数的对象,我应该使用 Class、Struct 还是 Dictionary?

swift - 无法将 SQL 查询结果从 bool 转换为 FMResult 集?

json - Codable 和 JSON 的问题

json - Swift 4 JSON Codable id 作为键

json - SwiftUI - 类型 'Service' 不符合协议(protocol) 'Decodable'

ios - 将 UIView 部分滑动以暴露另一个 View 并使暴露的 View 可交互?

Swift Observe 动态字典