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

What errors can happen when encode with Swift JSONEncoder

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.