skip to content

In Swift, what values can Any and AnyObject each hold, and what happens when a struct is stored as AnyObject?

level: middleimportance: should knowfreq 50%

answer

  1. one language type, one protocol
  2. classes only on one side
  3. explicit conversion, not implicit
  4. bridged or boxed, new identity

basics

~20 s

Any holds a value of any type, including structs, closures, metatypes and optionals. AnyObject holds class instances, so a struct needs an explicit as AnyObject, which bridges it or wraps it in a new box object.

solid answer

~50 s

`Any` is defined by the language and accepts every type, including function types, tuples and metatypes such as `Int.self`. `AnyObject` is the standard library protocol that every class implicitly conforms to, so it holds class instances, plus class metatypes on Apple platforms. Writing `let x: AnyObject = Screen(name: "home")` for a struct fails with `value of type 'Screen' expected to be instance of class or class-constrained type`. An explicit `Screen(name: "home") as AnyObject` compiles: a type that bridges, such as `String` or `Int` when Foundation is loaded, becomes `NSString` or `NSNumber`, and any other value is wrapped in an opaque box object. That box has its own identity, so two conversions are not `===`, and you get the struct back with `as? Screen`. Use `AnyObject` when you need reference behaviour such as `weak` or `===`.

code

swift · 17 lines
swift
struct Screen { let name: String }
final class Session {}

// Any: every kind of value, including structs, closures and metatypes.
let values: [Any] = [Screen(name: "home"), Session(), 42, { (x: Int) in x * 2 }, Int.self]

// AnyObject: class instances (and, on Apple platforms, class metatypes).
let objects: [AnyObject] = [Session(), Session.self]

// let bad: AnyObject = Screen(name: "home")
// error: value of type 'Screen' expected to be instance of class or class-constrained type

let boxed = Screen(name: "home") as AnyObject   // explicit: the struct is wrapped in a box object
print(type(of: boxed))                          // __SwiftValue (macOS, no Foundation import)
print((boxed as? Screen)?.name ?? "not a Screen")
print(boxed === (Screen(name: "home") as AnyObject))   // false: each conversion makes a new box
print(values.count, objects.count)

go deeper

for a junior

Recall that Any holds every kind of value and AnyObject holds class instances, and that you cast back with as?.

for a middle

Explain why a struct needs an explicit as AnyObject, and what the result is: a bridged Foundation object or an opaque box with its own identity.

for a senior

Spot code that relies on identity or mutation through a boxed struct, and choose AnyObject only where weak storage, === or an AnyObject-typed API needs it.

for a principal

Set a rule that untyped Any or AnyObject surfaces stay at module edges, such as an SDK adapter, and are converted to concrete types right there.

## Two top types with different definitions Swift offers two types for values whose concrete type is unknown, and they are not interchangeable. | | `Any` | `AnyObject` | |---|---|---| | Defined by | the language | the standard library, as a protocol | | Holds | a value of any type | class instances (and class metatypes on Apple platforms) | | Structs and enums | directly | only through an explicit `as AnyObject` | | `weak` storage | not allowed | allowed | | `===` identity | not available | available | - **`Any`** can hold a class, structure or enumeration instance, a tuple, a closure or function, a metatype such as `Int.self`, and an `Optional`. The compiler warns when an optional is implicitly coerced to `Any` (`expression implicitly coerced from 'Int?' to 'Any'`) and suggests `as Any` to make it explicit. - **`AnyObject`** is the protocol every class conforms to implicitly. Since Swift 3, Objective-C's `id` imports as `Any` rather than `AnyObject`, so `AnyObject` now appears mainly where an API really wants a class instance. Both keep the value's **dynamic type**, so `as?`, `as!` and `is` recover the concrete type later. ## Why a struct is not an AnyObject A struct has no object identity and no reference count, so Swift will not treat it as a class instance implicitly. These lines fail to compile in Swift 6.4: - `let x: AnyObject = Screen(name: "home")` reports `value of type 'Screen' expected to be instance of class or class-constrained type`. - `weak var listener: Any?` reports `'weak' must not be applied to non-class-bound 'Any'`. - `a === b` with `a` and `b` typed `Any` reports `argument type 'Any' expected to be an instance of a class or class-constrained type`. ## What an explicit `as AnyObject` does On Apple platforms the conversion compiles for any value, and what you get depends on the value: 1. **A class instance** is passed through unchanged; it already is an object. 2. **A bridged value type**, such as `String`, `Int`, `Array` or `Dictionary`, becomes its Foundation class (`NSString`, `NSNumber`, `NSArray`, `NSDictionary`) when Foundation is loaded on Apple platforms. 3. **Any other value**, such as your own struct, is wrapped in an immutable box object. On macOS, `type(of:)` on that box prints `__SwiftValue`; the name is a runtime detail, not API. The box has consequences: - Each conversion creates a new object, so `(screen as AnyObject) === (screen as AnyObject)` is false. - The box holds a copy; changing the original struct afterwards does not change the boxed value. - `boxed as? Screen` unwraps it again, because the box remembers the original Swift type. ## Getting the value back Both top types keep enough information to recover the original value, but they report it differently: - `values[0] as? Screen` and `boxed as? Screen` both succeed, because the cast machinery knows how to look inside a box. - `type(of:)` on an `Any` holding a struct reports the struct's type, `Screen`. - `type(of:)` on the boxed `AnyObject` reports the box class instead, so `type(of: boxed) == Screen.self` is false even though `boxed as? Screen` succeeds. - A bridged value comes back through its bridge: an `Int` converted with `as AnyObject` while Foundation is loaded is an `NSNumber`, and `as? Int` on it follows the `NSNumber` rules. Code that logs or switches on `type(of:)` therefore behaves differently for `Any` and `AnyObject` storage; prefer `as?` for decisions. ## Choosing between them - Prefer a concrete type, a generic parameter or a protocol whenever one fits; both top types push checks to run time. - Use **`Any`** for genuinely heterogeneous values, such as a legacy analytics SDK's `[String: Any]` payload or a `print`-style variadic argument. - Use **`AnyObject`** when reference semantics are the point: storing a `weak` reference, comparing identity with `===`, or calling an API whose parameter is typed `AnyObject`. - When a protocol's conformers must be classes, so that a delegate property can be `weak`, constrain the protocol with `AnyObject`; the Swift material on protocol requirements covers that form. ## Common mistakes - Believing `AnyObject` is just a shorter `Any`; it excludes every struct and enum unless you convert explicitly. - Expecting a struct converted with `as AnyObject` to keep reference identity or to reflect later mutations. - Assuming the bridged class is always the same; it depends on the value and on whether Foundation is loaded. - Using `[AnyObject]` for mixed values and then converting every element; `[Any]` already holds them.

  • Why does Session.self fit in an [AnyObject] array on Apple platforms?
    The standard library's documentation for `AnyObject` says it can be the concrete type for an instance of any class, class type or class-only protocol. With the Objective-C runtime on Apple platforms, a class's metatype converts to `AnyObject`, so `Session.self` fits. A struct's metatype does not: `Screen.self` is rejected as not a class instance, but it fits in `Any`.
  • When would you choose AnyObject over Any for a heterogeneous collection?
    When the collection needs reference behaviour: holding `weak` entries through a wrapper, de-duplicating by identity with `===`, or passing to an API whose parameter is typed `AnyObject`. For values that only need to be carried and cast back, `[Any]` holds everything without converting structs into boxes.

  • AnyObject is just a shorter spelling of Any.
  • A struct converts to AnyObject implicitly, like it does to Any.
  • Converting a struct with as AnyObject makes it a shared reference that sees later mutations.
  • Any cannot hold closures or metatypes.
  • Two as AnyObject conversions of the same struct are identical under ===.