skip to content

In Swift, when does Int32(_:) or Int(_:) trap during a numeric conversion, and when should you use init(exactly:), init(clamping:) or init(truncatingIfNeeded:) instead?

level: seniorimportance: should knowfreq 35%

answer

  1. the plain initializer assumes it fits
  2. nil, saturate or keep bits
  3. floats round toward zero first
  4. clamping takes integers only
  5. NaN and Double(Int.max)

basics

~20 s

Swift's plain integer initializer traps when the value does not fit, or is NaN or infinite. Use init?(exactly:) to get nil instead, init(clamping:) to saturate at min or max, and init(truncatingIfNeeded:) only when you want the low bits.

solid answer

~40 s

`Int32(_:)` assumes the value fits: from an integer it traps with "Not enough bits to represent the passed value", and from a `Double` it rounds toward zero, then traps if the result is out of range or the input is NaN or infinite. When an out-of-range value is a legitimate input, state the intent: `init?(exactly:)` returns `nil` for an unrepresentable value, or a fractional one from a float; `init(clamping:)` saturates to `min` or `max`; `init(truncatingIfNeeded:)` keeps the low bits, which suits hashing and binary formats but turns 5,000,000,000 into 705,032,704 in an `Int32`. Clamping and truncating accept only integer sources, so a `Double` needs `isFinite`, a range check or `rounded()` before `Int(_:)`.

code

swift · 15 lines
swift
let reportedSize: Int64 = 5_000_000_000             // from the server
let legacyField = Int32(exactly: reportedSize)      // nil: does not fit
let capped = Int32(clamping: reportedSize)          // 2147483647
let lowBits = UInt8(truncatingIfNeeded: 300)        // 44: keeps the low 8 bits
print(legacyField as Any, capped, lowBits)          // nil 2147483647 44

let fraction = 0.736
let percent = Int(fraction * 100)                   // 73: rounds toward zero
print(percent, Int(exactly: 73.6) as Any, Int(exactly: 73.0) as Any)   // 73 nil Optional(73)

let corrupt = Double.nan                            // e.g. 0 bytes of 0 total
// Int(corrupt) would trap: Double value cannot be converted to Int
// because it is either infinite or NaN
let safePercent = corrupt.isFinite ? Int(corrupt * 100) : 0
print(safePercent)                                  // 0

go deeper

for a junior

Know that converting a value that does not fit, such as 300 into Int8, crashes the program instead of producing a wrong number.

for a middle

Name the four conversion initializers and what each does with an out-of-range value, and that floats round toward zero first.

for a senior

Choose the conversion per data source, validating untrusted sizes with init?(exactly:) and guarding Doubles for NaN and the Int.max boundary.

for a principal

Make conversion policy explicit at system boundaries, so where a value traps, saturates or is rejected is a recorded decision rather than an accident.

## The plain initializer checks and traps Every Swift integer type has a family of **conversion initializers**. The plain one, `Int32(_:)` or `Int(_:)`, assumes the value fits and **traps at run time** when it does not. The messages come straight from the standard library: - from another integer: `Int8(x)` with `x == 300` stops with "Not enough bits to represent the passed value"; - from a floating-point value that is NaN or infinite: "Double value cannot be converted to Int because it is either infinite or NaN"; - from a floating-point value out of range: "… because the result would be greater than Int.max" (or "less than Int.min", or "less than UInt.min" for a negative value going into `UInt`). From a floating-point source the value is **rounded toward zero first** and the range is checked after, so `Int8(127.75)` is `127` while `Int8(128.25)` traps. When the argument is a literal the compiler catches the problem before the program runs: `Int8(300)` fails with "integer literal '300' overflows when stored into 'Int8'". The trap is deliberate. A silently wrong number in a file size, an index or a balance is worse than a crash with a clear message, so the plain initializer is right when an out-of-range value would be a programmer error. ## Four initializers, four intents When an out-of-range value is a **legitimate input**, pick the initializer that states what should happen: | Initializer | Accepts | Out of range or inexact | Example | |---|---|---|---| | `init(_:)` | integers and floating-point | traps; floats round toward zero first | `Int(73.6)` is `73` | | `init?(exactly:)` | integers and floating-point | returns `nil`; for floats also `nil` if there is a fractional part | `Int(exactly: 73.6)` is `nil` | | `init(clamping:)` | integers only | saturates to `min` or `max` | `Int32(clamping: Int64(5_000_000_000))` is `2147483647` | | `init(truncatingIfNeeded:)` | integers only | keeps the low bits, sign-extends when widening | `UInt8(truncatingIfNeeded: 300)` is `44` | Reading the table as intents: 1. **`init?(exactly:)`** answers "is this value representable exactly?" Use it for untrusted input: a byte count from a server that must fit a 32-bit field, a JSON number that must be a whole count. The optional forces the caller to handle the failure. 2. **`init(clamping:)`** answers "give me the nearest representable value". Use it when saturation is the honest result, such as a progress counter or a legacy 32-bit field that should show the maximum rather than garbage. 3. **`init(truncatingIfNeeded:)`** answers "give me these bits". It exists for hashing, checksums, binary protocols and bit manipulation, where the bit pattern is the point. It is not a way to make a number fit: `Int32(truncatingIfNeeded: Int64(5_000_000_000))` is `705032704`, a plausible-looking wrong answer. ## Floating-point sources need extra care `init(clamping:)` and `init(truncatingIfNeeded:)` accept only `BinaryInteger` sources; `Int(clamping: 1e20)` fails to compile because the initializer "requires that 'Double' conform to 'BinaryInteger'". For a `Double` you have: - `Int(_:)` after your own checks, typically `value.isFinite` plus a range check; - `Int(exactly:)` when the value must be a whole number already; - rounding first, `Int(value.rounded())`, when the nearest integer is wanted rather than truncation. One boundary is easy to miss: `Double(Int.max)` cannot represent 9,223,372,036,854,775,807 exactly and rounds up to 2^63, so `Int(Double(Int.max))` traps with "… greater than Int.max". A hand-written clamp for `Double` to `Int` therefore needs care at the top of the range; clamping to `Int32` is safe because every `Int32` value is exactly representable as a `Double`. ## A file-transfer example A transfer screen receives `reportedSize: Int64` from a server and shows a percentage: - the legacy 32-bit field uses `Int32(exactly: reportedSize)` and reports an error when it gets `nil`, or `Int32(clamping:)` when the field should simply cap; - the percentage `Int(fraction * 100)` is guarded with `fraction.isFinite`, because a transfer of 0 bytes out of 0 makes `fraction` NaN (0.0 / 0.0) and the conversion would trap; - the size and percentage fields never use `truncatingIfNeeded`, because no bit pattern is being preserved there; - a checksum over the file's bytes, if the protocol defines one as a 32-bit sum, is the one place `truncatingIfNeeded` belongs, because there the low bits are the specified result. Overflow in arithmetic itself, and the wrapping operators `&+` and `&*`, belong with Swift's operators; this lesson is about the moment one numeric type becomes another.

  • Why does `Int(Double(Int.max))` trap in Swift?
    A `Double` has a 52-bit stored significand, so it cannot represent 9,223,372,036,854,775,807 exactly; `Double(Int.max)` rounds up to 2^63. Converting that back exceeds `Int.max`, so `Int(_:)` traps with "Double value cannot be converted to Int because the result would be greater than Int.max". A hand-written clamp from `Double` to `Int` has to handle the top of the range explicitly.
  • Is `Int32(truncatingIfNeeded: bigCount)` a safe way to fit a 64-bit byte count into a 32-bit field?
    No. It keeps the low 32 bits, so 5,000,000,000 becomes 705,032,704, a believable but wrong size with no error. Use `Int32(exactly:)` and handle `nil`, or `Int32(clamping:)` if saturating at `Int32.max` is acceptable. `truncatingIfNeeded` is for code where the bit pattern itself is the point.

  • Int32(_:) silently wraps a too-large Int64, like a C cast.
  • init(clamping:) also accepts Double, so it can clamp a measurement.
  • Int(exactly: 73.6) rounds to 74.
  • init(truncatingIfNeeded:) keeps the value whenever possible and saturates otherwise.
  • Converting NaN to Int gives 0.