AnyValue
public struct AnyValue
extension AnyValue: CustomStringConvertible, CustomDebugStringConvertible
A wrapper for a value of any type, with efficient access and inline storage of bounded size for small values.
Existential types such as Any
provide the storage characteristics of AnyValue
, but many
operations on existentials optimize poorly, so
AnyValue
may be needed to achieve efficient access.
Using enums
and no existential, it is possible to build such storage for:
- types that are trivially copiable (such as Int), or
- collections of elements with the inline storage being (roughly) a multiple of the element
size.
You might consider using the
enum
approach where applicable.
-
Creates an instance that stores
x
.Postcondition
wherea
is the created instance,a.storedType == T.self
, anda[T.self]
is equivalent tox
.Declaration
Swift
public init<T>(_ x: T)
-
The type of the value stored in
self
.Declaration
Swift
public var storedType: Any.Type { get }
-
Accesses the
T
stored inself
.Requires
storedType == T.self
.Declaration
Swift
@inline(__always) public subscript<T>(_: Type<T>) -> T { get set }
-
Unsafely accesses the
T
stored inself
.Requires
storedType == T.self
.Declaration
Swift
@inline(__always) public subscript<T>(unsafelyAssuming _: Type<T>) -> T { get set }
-
Stores
x
inself
.This may be more efficient than
self = AnyValue(x)
because it uses the same allocated buffer when possible for large types.Declaration
Swift
public mutating func store<T>(_ x: T)
-
The stored value.
This property can be useful for interoperability with the rest of Swift, especially when you don’t know the full dynamic type of the stored value.
Declaration
Swift
public var asAny: Any { get }
-
A textual representation of this instance.
Declaration
Swift
public var description: String { get }
-
A string, suitable for debugging, that represents the instance.
Declaration
Swift
public var debugDescription: String { get }