Reputation: 2094
JSONEncoder
method func encode<T>(_ value: T) throws -> Data where T : Encodable
is throwable.
I wonder why is it throwable: If the value to encode is not conform to Encodable
, it can't pass compiler checking, so it should encounter no errors at runtime.
Upvotes: 5
Views: 1865
Reputation: 9395
From JSONEncoder
's 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.
Debug descriptions for all errors:
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.
Upvotes: 7