KeyedEncodingContainer
extension KeyedEncodingContainer
Extensions for KeyedEncodingContainer to support encoding of dynamic dictionaries and arrays
with Sendable values, enabling flexible JSON serialization.
-
Encodes a dictionary with string keys and
Sendablevalues if present and non-empty.This method creates a nested container and encodes each value based on its runtime type, supporting Int, String, Double, Float, Bool, arrays, and nested dictionaries.
Throws
EncodingErrorif any value cannot be encodedDeclaration
Swift
public mutating func encodeIfPresent(_ value: [String : any Sendable]?, forKey key: KeyedEncodingContainer<K>.Key) throwsParameters
valueThe optional dictionary to encode
keyThe coding key to encode to
-
Encodes an array of
Sendablevalues if present.This method attempts to encode the array as a homogeneous collection based on its runtime type. If the array is heterogeneous or contains dictionaries, it creates a nested unkeyed container to encode each element individually.
Throws
EncodingErrorif the array cannot be encodedDeclaration
Swift
public mutating func encodeIfPresent(_ value: [any Sendable]?, forKey key: KeyedEncodingContainer<K>.Key) throwsParameters
valueThe optional array to encode
keyThe coding key to encode to
View on GitHub