skip to content

In Swift, why does a JSONSerialization payload's 2.5 fail as? Int while 3.0 succeeds, and what does as? [Int] check?

level: seniorimportance: should knowfreq 35%

answer

  1. Foundation objects behind Any
  2. can it be expressed exactly
  3. booleans are numbers too
  4. every element, all or nothing

basics

~20 s

JSONSerialization stores numbers as NSNumber, and a cast to a Swift numeric type succeeds only when the value fits that type exactly: 3.0 becomes 3, 2.5 gives nil. as? [Int] checks every element and returns nil if any one fails.

solid answer

~50 s

`JSONSerialization` returns Foundation objects: `NSDictionary`, `NSArray`, `NSString`, `NSNumber` and `NSNull`, seen through `Any`. Casting an `NSNumber` to a Swift numeric type asks whether the stored value can be expressed **exactly** in that type, the rule SE-0170 set in Swift 4.0: `3.0 as? Int` gives `3`, `2.5 as? Int` gives nil, and `300 as? Int8` gives nil instead of wrapping. JSON `true` is an `NSNumber` too, so it casts to `Int` as `1`, and `1 as? Bool` is `true` while `2 as? Bool` is nil. A collection cast such as `json["ids"] as? [Int]` checks every element and returns nil if a single element fails. JSON `null` arrives as `NSNull`, not as a nil optional, so `as? String` gives nil and `is NSNull` is true. Going the other way, `title as NSString` is an unconditional bridging cast.

code

swift · 18 lines
swift
import Foundation

let body = #"{"count": 3, "ratio": 2.5, "whole": 3.0, "opted_in": true, "ids": [1, 2, 3], "mixed": [1, "a"], "referrer": null}"#
let json = try! JSONSerialization.jsonObject(with: Data(body.utf8)) as! [String: Any]

print(json["count"] as? Int as Any)       // Optional(3)
print(json["count"] as? Double as Any)    // Optional(3.0): 3 is exactly representable
print(json["ratio"] as? Int as Any)       // nil: 2.5 would lose its fraction
print(json["whole"] as? Int as Any)       // Optional(3)
print(json["opted_in"] as? Int as Any)    // Optional(1): a JSON true is an NSNumber too
print(json["ids"] as? [Int] as Any)       // Optional([1, 2, 3]): every element checked
print(json["mixed"] as? [Int] as Any)     // nil: one element failed, the whole cast fails
print(json["referrer"] is NSNull)         // true: JSON null is NSNull, not nil

let title = "Checkout"
let nsTitle = title as NSString           // bridging upcast: as, no ? or !
let back = nsTitle as String              // NSString to String is also an unconditional as
print(back)

go deeper

for a junior

Recall that JSONSerialization returns Foundation objects behind Any and that you read fields with as? String, as? Int and similar casts.

for a middle

Explain the exact-representation rule for NSNumber casts and why a collection cast checks every element and is all or nothing.

for a senior

Diagnose fields that silently became nil after a producer change, and harden the adapter so numeric shape and NSNull are handled on purpose.

for a principal

Push untyped JSON handling to one adapter per SDK and replace casts with typed decoding where the dependency allows it.

## What JSONSerialization hands back A legacy analytics SDK that parses JSON with `JSONSerialization.jsonObject(with:)` gives you an `Any` that you usually cast to `[String: Any]`. The values inside are **Foundation objects**, and every later cast is a **bridging cast** between a Foundation class and a Swift type: | JSON | Foundation object | Typical Swift cast | |---|---|---| | object | `NSDictionary` | `as? [String: Any]` | | array | `NSArray` | `as? [Int]`, `as? [Any]` | | string | `NSString` | `as? String` | | number, `true`, `false` | `NSNumber` | `as? Int`, `as? Double`, `as? Bool` | | `null` | `NSNull` | `is NSNull` | ## NSNumber casts ask "does it fit exactly?" `NSNumber` is an untyped numeric box. Since Swift 4.0 (SE-0170), `as?` on it means "can the stored value be expressed safely as the type I asked for?". Swift 6.4 on macOS gives: - `3 as? Double` is `3.0`, and `3.0 as? Int` is `3`: both values are exactly representable. - `2.5 as? Int` is nil, because the fraction would be lost; there is no truncation and no rounding. - `300 as? Int8` is nil, while `300 as? Int16` is `300`; out-of-range values do not wrap. - JSON `true` casts to `Bool` as `true` and to `Int` as `1`. - `1 as? Bool` is `true`, while `2 as? Bool` is nil. The rule exists because an `NSNumber` does not reliably remember which C type created it; Foundation may store small values in a compact form. Swift therefore judges the **value**, not the producer's intent, and that is why JSON `true` and the number `1` can both satisfy `as? Bool` and `as? Int`. This rule is what lets a server change `"count": 3` to `"count": 3.0` without breaking an `as? Int`, and it is also why a field that later carries `2.5` silently becomes nil. `is` follows the same logic as `as?`. ## Collection casts are all or nothing Casting an array checks its elements. For a Swift array, the standard library documents `source as? [TargetElement]` as converting each element and returning nil if any element fails, with complexity **O(n)**; a bridged `NSArray` from `JSONSerialization` gives the same all-or-nothing results: - `json["ids"] as? [Int]` with `[1, 2, 3]` gives `[1, 2, 3]`. - `json["mixed"] as? [Int]` with `[1, "a"]` gives nil; you do not get the elements that matched. - `json["mixed"] as? [Any]` succeeds and leaves the per-element casts to you. - A forced `as! [String]` on an `NSArray` holding a number traps, reporting that an `NSNumber` could not be cast to `NSString`. On a large payload, repeating `as? [Int]` in a loop repeats the element-by-element check every time; cast once and keep the typed array. ## Which direction needs which operator Bridging is asymmetric, and Swift 6.4 enforces it at compile time: | Conversion | Spelling that compiles | |---|---| | `String` to `NSString` | `title as NSString` | | `NSString` to `String` | `nsTitle as String` | | `Int` to `NSNumber` | `42 as NSNumber` | | `NSNumber` to `Int` | `n as? Int` or `n as! Int` | | `NSArray` to `[String]` | `a as? [String]` or `a as! [String]` | `let i = n as Int` fails with `'NSNumber' is not convertible to 'Int'`, and `let s: NSString = title` fails too, because implicit bridging conversions were removed in Swift 3 (SE-0072). ## Hardening the SDK adapter 1. Cast the top level once: `guard let json = object as? [String: Any] else { … }`. 2. Read each field with the type the contract names, and decide what a nil means: missing, `NSNull`, or the wrong numeric shape. 3. Accept both `Int` and `Double` where the producer is loose, for example `(json["ratio"] as? Double) ?? 0`, instead of assuming integers stay integers. 4. Convert the dictionary into a typed struct at the boundary; the Swift material on `Codable` covers decoding JSON without casts at all. ## Common mistakes - Expecting `2.5 as? Int` to truncate to `2`; it returns nil. - Treating JSON `null` as a nil optional; it is an `NSNull` instance. - Assuming `as? [Int]` drops bad elements; one bad element fails the whole cast. - Assuming `as? Bool` only matches JSON `true` and `false`; any `NSNumber` holding 0 or 1 also casts.

  • Why might a field that worked as as? Int for months start returning nil without any client change?
    Because the cast checks the value, not the JSON token's shape. While the server sends whole numbers, `as? Int` succeeds even for `3.0`; once it sends `2.5`, or a number outside `Int`'s range, the exact-representation rule makes the cast nil. Read loosely typed fields as `Double` or validate them explicitly.
  • Can a cast tell a JSON true apart from the number 1 in a JSONSerialization payload?
    Not reliably. Both arrive as `NSNumber`, and the cast asks only whether the value fits: `as? Int` on `true` gives `1` and `as? Bool` on `1` gives `true`. When the distinction matters, decode into a typed struct; `JSONDecoder` reports a `typeMismatch` when a field declared `Int` holds a JSON boolean.

  • 2.5 as? Int truncates to 2, like Int(2.5) does.
  • A JSON null in a [String: Any] reads back as a nil optional.
  • as? [Int] returns the elements that matched and skips the rest.
  • A JSON true can only be cast to Bool.
  • NSNumber to Int works with a plain as, like String to NSString.