JSONEncoder
方法 func encode<T>(_ value: T) throws -> Data where T : Encodable
是可抛出的。
我想知道为什么它是可抛出的:如果要编码的值不符合 Encodable
,它无法通过编译器检查,因此在运行时应该不会遇到任何错误。
最佳答案
来自 JSONEncoder
的 source 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/