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 Sendable values 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

    EncodingError if any value cannot be encoded

    Declaration

    Swift

    public mutating func encodeIfPresent(_ value: [String : any Sendable]?, forKey key: KeyedEncodingContainer<K>.Key) throws

    Parameters

    value

    The optional dictionary to encode

    key

    The coding key to encode to

  • Encodes an array of Sendable values 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

    EncodingError if the array cannot be encoded

    Declaration

    Swift

    public mutating func encodeIfPresent(_ value: [any Sendable]?, forKey key: KeyedEncodingContainer<K>.Key) throws

    Parameters

    value

    The optional array to encode

    key

    The coding key to encode to