skip to content

A Swift analytics payload typed [String: Any] stores an Optional that is nil: why does comparing it to nil return false, and what do as? casts do with it?

level: seniorimportance: should knowfreq 28%

answer

  1. an Optional is a value too
  2. the outer Any is never nil
  3. casts look through the stored Optional
  4. a dictionary subscript takes Any?

basics

~20 s

An Any can hold an Optional as its value, so an Any containing Optional.none is not nil and == nil is always false. A cast such as as? Int looks inside: a stored nil gives nil, a stored 5 gives 5.

solid answer

~40 s

`Any` represents values of any type, including optional types, so `userID as Any` stores an `Optional<Int>.none` as an ordinary value. The `Any` holding it is not optional, which is why `stored == nil` is always false; Swift 6.4 warns `comparing non-optional value of type 'Any' to 'nil' always returns false`. Casts unwrap the stored Optional: `stored as? Int` is nil for a stored nil and `5` for a stored `5`, while `stored is Int?` is true and `stored as? Int?` gives a non-nil `Int??` wrapping nil. Writing an optional through a `[String: Any]` subscript behaves differently again: the subscript takes `Any?`, so `payload["user_id"] = userID` with a nil `userID` removes the key instead of storing anything. Decide the payload's rule for missing values at the write site.

code

swift · 22 lines
swift
let userID: Int? = nil
let campaign: String? = "spring"

var payload: [String: Any] = [:]
payload["user_id"] = userID              // Int? converts to Any?: nil removes the key
print(payload.keys.sorted())             // []

payload["user_id"] = userID as Any       // stores Optional<Int>.none inside Any
payload["campaign"] = campaign as Any    // stores Optional<String>.some("spring") inside Any

let id = payload["user_id"]!             // static type Any, dynamic type Optional<Int>
print(id)                                // nil
print(id as? Int as Any)                 // nil: the cast looks inside and finds no Int
print(id is Int?)                        // true

let tag = payload["campaign"]!
print(tag)                               // Optional("spring")
print(tag as? String as Any)             // Optional("spring"): as? unwrapped the inner Optional

protocol OptionalValue { var isNone: Bool { get } }
extension Optional: OptionalValue { var isNone: Bool { self == nil } }
print((id as? any OptionalValue)?.isNone == true)   // true

go deeper

for a junior

Recall that an Optional is itself a value, so putting a nil Optional into Any produces a non-nil Any.

for a middle

Explain how casts from Any unwrap a stored Optional, and why the dictionary subscript's Any? turns a nil assignment into a removed key.

for a senior

Diagnose payloads that lose or mangle fields because optionals were stored in Any, and fix the write site rather than the consumer.

for a principal

Argue for converting untyped payloads to typed structs at the boundary, so optional handling is checked by the compiler instead of by convention.

## How an Optional ends up inside Any `Optional<Wrapped>` is an ordinary enum with the cases `none` and `some(Wrapped)`, and the book notes that `Any` represents values of any type, **including optional types**. An optional can reach an `Any` in several ways: 1. An explicit conversion, `userID as Any`, which is also how you silence the warning `expression implicitly coerced from 'Int?' to 'Any'`. 2. An implicit conversion, which compiles with that warning. 3. A generic function whose `T` is bound to `Int?` and which then stores its argument as `Any`. 4. An array or tuple element copied into an `[Any]` from optional-typed sources. Once inside, the `Any` value has the **dynamic type** `Optional<Int>`. It carries a value, and that value happens to be `.none`. ## Why `== nil` returns false `stored` is typed `Any`, not `Any?`. A non-optional value is never nil, whatever it contains, so `stored == nil` is always false and Swift 6.4 says so: ```plaintext warning: comparing non-optional value of type 'Any' to 'nil' always returns false ``` Wrapping it again does not help: `(stored as Any?) == nil` is also false, because that adds an outer `Optional` around a value that exists. ## How casts treat the stored Optional Casting from `Any` looks through optionals in the stored value, as the table shows for `id` holding `Optional<Int>.none` and `tag` holding `Optional("spring")`: | Expression | Result | |---|---| | `id as? Int` | `nil` | | `id is Int` | `false` | | `id is Int?` | `true` | | `id as? Int?` | `Optional(nil)`, a non-nil `Int??` | | `tag as? String` | `Optional("spring")` | | `print(tag)` | `Optional("spring")` | So a consumer that only asks `as? Int` cannot tell "absent", "present but nil" and "present but a different type" apart: all three give nil. ## The dictionary subscript trap Writing into a `[String: Any]` goes through a subscript whose value type is `Any?`. An `Int?` converts to `Any?` by mapping `nil` to `nil`, so: - `payload["user_id"] = userID` with a nil `userID` **removes** the key, or leaves it absent. - `payload["user_id"] = userID as Any` **stores** an `Optional<Int>.none` under the key. Two lines that look alike produce different payloads, and a legacy analytics SDK that serialises the dictionary may then drop the field, send `null` or crash on a value it cannot encode. ## Where it shows up in real code The pattern rarely looks as deliberate as `userID as Any`. Common sources: - A generic helper such as `func track<T>(_ name: String, _ value: T)` that builds `[String: Any]` from its arguments: called with an `Int?`, it stores an optional without any warning, because `T` is already `Int?` and the conversion from `T` to `Any` is not an optional-to-`Any` coercion. - `Mirror(reflecting: model).children`, whose values are typed `Any`: every optional property of the model arrives as an `Any` holding an `Optional`. - String interpolation of such a value, which writes `Optional("spring")` or `nil` into a log line or an analytics label instead of `spring`. ## Detecting a nil hidden in Any When you cannot change the producer, test for the optional explicitly: - Declare a small protocol with an `isNone` property, conform `Optional` to it, and check `(value as? any OptionalValue)?.isNone == true`. - Ask `Mirror(reflecting: value).displayStyle == .optional` and check whether its `children` collection is empty. - Cast to the exact optional type you expect, `value as? Int?`, and unwrap twice. ## Designing payloads so it does not happen - Pick one rule for missing values at the write site: omit the key, or store an explicit sentinel the consumer understands, such as `NSNull()` for a Foundation serialiser. - Unwrap before storing: `if let userID { payload["user_id"] = userID }`. - Treat the `implicitly coerced` warning as a defect, never as noise to silence with `as Any`. - Keep `[String: Any]` at the SDK boundary and convert it to a typed struct immediately.

  • Why does as? String on an Any holding Optional("spring") succeed when the dynamic type is Optional<String>?
    Dynamic casts from `Any` unwrap optionals in the source value before matching, so an `Optional<String>.some("spring")` satisfies a cast to `String`. Nested optionals unwrap too: an `Any` holding `Optional(Optional(5))` casts to `Int` as `5`. Only a stored `none` makes the cast fail.
  • How can a consumer of a [String: Any] tell an absent key from a key holding a nil Optional?
    Check the key first with `payload[key]`, which is nil only when the key is absent. Then test the stored value for an optional, for example by casting to a protocol that `Optional` conforms to and reading its `isNone` property, or by checking `Mirror(reflecting:).displayStyle == .optional` with no children.

A parcel labelled "contents: anything" that holds an empty envelope is not an empty parcel. Asking whether the parcel is empty says no; opening it and asking for a letter finds none.

  • An Any holding a nil Optional compares equal to nil.
  • Assigning a nil Int? into a [String: Any] stores a nil value under the key.
  • as? Int on an Any holding Optional(5) fails because the type is Optional<Int>.
  • Wrapping the value with as Any? makes the nil check work.
  • The implicit coercion warning is harmless noise to silence with as Any.