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
AnyValuewrapper 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
valueThe 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:
- Null values (represented as NSNull)
- Bool (checked first to prevent decoding as Int 1/0)
- Int
- Double
- String
- Array (recursively decoded as [AnyValue])
- Dictionary (recursively decoded as [String: AnyValue])
Throws
DecodingError.dataCorruptedif the value is not one of the supported typesDeclaration
Swift
public init(from decoder: Decoder) throwsParameters
decoderThe 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.invalidValueif the value type is not supportedDeclaration
Swift
public func encode(to encoder: Encoder) throwsParameters
encoderThe encoder to write data to
View on GitHub