AnyValue

public struct AnyValue : Codable, @unchecked Sendable

A type-erased wrapper for any Codable value.

This wrapper allows heterogeneous data types to be stored in the same dictionary while maintaining Codable compliance for JSON serialization.

Supported Types

  • Primitives: Bool, Int, Double, String
  • Collections: Arrays and Dictionaries (recursively)
  • Null values: NSNull representation

Usage

let anyValue = AnyValue("Hello World")
let originalValue = anyValue.value as? String
  • The wrapped value of any type.

    This property holds the actual value that has been type-erased. The value can be retrieved by casting it to its original type.

    Declaration

    Swift

    public let value: Any
  • Creates a new AnyValue wrapper around the provided value.

    Use this initializer to wrap any value that you want to store in a heterogeneous collection while maintaining Codable compliance.

    Declaration

    Swift

    public init(_ value: Any)

    Parameters

    value

    The value to wrap. Should be one of the supported types: Bool, Int, Double, String, Array, Dictionary, or NSNull

  • Decodes a value from the given decoder.

    This initializer attempts to decode the value by trying each supported type in order:

    1. Null values (represented as NSNull)
    2. Bool (checked first to prevent decoding as Int 1/0)
    3. Int
    4. Double
    5. String
    6. Array (recursively decoded as [AnyValue])
    7. Dictionary (recursively decoded as [String: AnyValue])

    Throws

    DecodingError.dataCorrupted if the value is not one of the supported types

    Declaration

    Swift

    public init(from decoder: Decoder) throws

    Parameters

    decoder

    The decoder to read data from

  • Encodes the wrapped value to the given encoder.

    This method encodes the value based on its runtime type. Special handling is provided for:

    • NSNull: Encoded as a JSON null value
    • NSNumber: Properly distinguished between Bool, Int, and Double based on ObjC type
    • Bool: Checked first to prevent encoding as Int (1/0)
    • Primitive types: Int, Double, String
    • Collections: Arrays and Dictionaries (recursively encoded as AnyValue)

    Throws

    EncodingError.invalidValue if the value type is not supported

    Declaration

    Swift

    public func encode(to encoder: Encoder) throws

    Parameters

    encoder

    The encoder to write data to