skip to content

Operators, Overflow and Ranges

Swift traps on integer overflow unless you use the &+ family, offers closed, half-open and one-sided ranges, and lets you declare operators. Interviewers ask about overflow and ranges.

on this pageshow

explore

questions

6

In Swift, how do the closed range `a...b`, the half-open range `a..<b` and one-sided ranges like `items[2...]` differ, and when does a range trap?

level: juniorimportance: must knowfreq 70%

answer

  1. inclusive versus exclusive upper end
  2. five distinct range types
  3. collection fills in the missing bound
  4. lower bound must not exceed upper
  5. slices are bounds-checked too

basics

~20 s

a...b is a ClosedRange including b; a..<b is a Range stopping before b, so a..<a is empty. One-sided forms like items[2...] take the missing bound from the collection. Inverted bounds trap, as does slicing past an array's indices.

solid answer

~40 s

`a...b` builds a `ClosedRange` containing both ends, which suits inclusive domains like `1...6`. `a..<b` builds a `Range` that stops before `b`, which matches zero-based indices: `0..<items.count` is safe even for an empty array, because `0..<0` is a valid empty range. One-sided ranges are their own types (`PartialRangeFrom` for `2...`, `PartialRangeThrough` for `...2`, `PartialRangeUpTo` for `..<2`), and a collection subscript fills in the missing bound. Two traps matter. Forming a range whose lower bound exceeds its upper bound fails the precondition "Range requires lowerBound <= upperBound" at run time, even for a literal like `5..<2`. Slicing with a range outside the array's `indices` traps with "Array index is out of range"; for paging, clamp with `clamped(to: items.indices)` or use `dropFirst(_:)` and `prefix(_:)`.

code

swift · 16 lines
swift
let scores = Array(1...25)          // ClosedRange: 1 through 25
let pageSize = 10

func page(_ number: Int) -> ArraySlice<Int> {
    let start = number * pageSize
    let wanted = start..<(start + pageSize)   // half-open: excludes the end
    return scores[wanted.clamped(to: scores.indices)]
}

print(Array(page(2)))       // [21, 22, 23, 24, 25]
print(page(2).startIndex)   // 20: the slice keeps the array's indices
print(Array(page(3)))       // []
print(scores[22...])        // [23, 24, 25]
print(scores[..<3])         // [1, 2, 3]
print(scores[...2])         // [1, 2, 3]
// print(scores[20..<30])   // would trap: Array index is out of range

go deeper

for a junior

Recall which operator includes its upper end, that 3..<3 is empty while 3...3 holds one value, and that an inverted range traps instead of counting down.

for a middle

Explain the five range types, how a subscript fills in a one-sided range's missing bound, and why a half-open range models an empty collection without special cases.

for a senior

Show how ranges built from computed bounds trap in production, and reach for clamped(to:), prefix and dropFirst for paging instead of hand-written index arithmetic.

for a principal

Treat range traps as bounds checks the team relies on: decide where computed ranges get validated, and prefer collection APIs that cannot overrun over manual index math.

## Two bounded range operators Swift spells ranges with operators, and each operator produces its own standard-library type: | Expression | Type | Contains | Can it be empty? | |---|---|---|---| | `1...5` | `ClosedRange<Int>` | 1, 2, 3, 4, 5 | No: at least one value | | `1..<5` | `Range<Int>` | 1, 2, 3, 4 | Yes: `3..<3` is empty | | `2...` | `PartialRangeFrom<Int>` | 2 and everything above | not applicable | | `...2` | `PartialRangeThrough<Int>` | everything up to and including 2 | not applicable | | `..<2` | `PartialRangeUpTo<Int>` | everything below 2 | not applicable | The **closed range operator** `a...b` includes both ends. It reads naturally for inclusive value domains: dice faces `1...6`, the days of a month `1...31`, a percentage `0...100`. Because both ends are in it, a `ClosedRange` always holds at least one value; there is no closed way to write "nothing". The **half-open range operator** `a..<b` includes `a` and stops just before `b`. That shape matches zero-based indices, which is why `0..<items.count` is the idiomatic way to walk an array's positions: when the array is empty, `0..<0` is a valid, empty range and a loop over it runs zero times. Half-open ranges also tile cleanly: `0..<10` followed by `10..<20` covers twenty values with no overlap and no gap, which is exactly what paging needs. The counts follow from the definitions: `(1...5).count` is 5 and `(1..<5).count` is 4. ## One-sided ranges A **one-sided range** omits one bound. It is an ordinary value (you can store `...5` in a constant and call `contains(_:)` on it), but its everyday job is subscripting a collection, where the collection supplies the missing bound: - `items[2...]` runs from index 2 to the end; the array fills in its `endIndex`. - `items[...2]` runs from the start through index 2 inclusive. - `items[..<2]` runs from the start up to, but not including, index 2. These read better than `items[2..<items.count]` and cannot get the end wrong. Two iteration rules follow from the missing bound: - You can loop over `2...`, but it never ends on its own, so the loop needs its own `break`. - You cannot loop over `..<5` or `...5`, because there is no first value. The compiler says `for-in loop requires 'PartialRangeUpTo<Int>' to conform to 'Sequence'`. ## When a range traps Ranges are checked, not trusted. Three situations stop the program: 1. **Inverted bounds.** Both `..<` and `...` check `lowerBound <= upperBound` and fail with `Fatal error: Range requires lowerBound <= upperBound`. The check is a run-time precondition, so even a literal such as `let r = 5..<2` compiles and then traps. To count down, reverse a valid range, as in `(0..<5).reversed()`, rather than writing the bounds backwards. 2. **Slicing past the indices.** On a 25-element array, `items[20..<30]` compiles and then traps with `Fatal error: Array index is out of range`. A one-sided range does not help when its one stated bound is itself outside the array: `items[26...]` traps too (the array resolves it to the inverted range `26..<25`), while `items[25...]` is a valid empty slice. 3. **Computed bounds.** Most real range traps come from arithmetic. `0...items.count - 1` on an empty array becomes `0...-1`, an inverted range; `start..<start + pageSize` on the last page runs past the end. In an optimized build the process still traps, though the message text may not be printed. ## Paging a list safely The paginated-list case shows the pattern: build the page you want as a half-open range, then clamp it to what exists. - `wanted.clamped(to: scores.indices)` shrinks the range to the array's valid indices; a page past the end becomes an empty range instead of a trap. - `scores.dropFirst(start).prefix(pageSize)` expresses the same page without index arithmetic, because both methods stop at the end of the collection. - The result is an `ArraySlice` that keeps the original array's indices: the third page starts at index 20, not 0. Wrap it in `Array(...)` before handing it to code that assumes zero-based positions. How slices share storage with their array is covered with arrays and slices. ## Choosing between them - Use `..<` for positions and counts: indices, offsets, pages, "the first n". - Use `...` for inclusive value domains: ratings, ages, a window of days. - Use the one-sided forms for "from here to the end" and "the leading part" of a collection.

  • Why is `0..<items.count` safer than `0...items.count - 1` when the array might be empty?
    For an empty array, `0..<0` is a valid empty range, so a loop over it runs zero times. `0...items.count - 1` becomes `0...-1`, whose lower bound exceeds its upper bound, so merely forming it traps with "Range requires lowerBound <= upperBound". A half-open range can say "nothing"; a closed range cannot.
  • Does `items[3...]` trap on a three-element array?
    No. The array resolves `3...` to `3..<3`, because its `endIndex` is 3, and that is a valid empty slice. `items[4...]` does trap, because its stated lower bound lies past `endIndex`. A one-sided range only removes the risk on the side you omitted.

  • Writing 5..<2 is a compile error, so inverted ranges never reach run time
  • The closed range 3...3 is empty
  • Slicing items[20..<30] on a shorter array returns whatever elements exist
  • You can loop over ..<5 the same way as 0..<5
  • A slice taken with items[20...] starts again at index 0
  • One-sided ranges only work inside a collection subscript
open as a page

A game's Int32 score counter crashes after a very long session; what does Swift do on integer overflow, and when is `&+` the right fix?

level: middleimportance: must knowfreq 66%

basics

~20 s

Swift's +, - and * trap at run time on overflow, and the compiler rejects overflows it can compute. &+, &- and &* wrap in two's complement: right for hashes and checksums, wrong for a score, which should clamp or use a wider type.

open as a page

Why does Swift reject `if count { … }` for an Int and `1 < x < 10`, and how do `&&` and `?:` evaluate?

level: juniorimportance: should knowfreq 45%

basics

~20 s

A Swift boolean condition must be a Bool, and comparison operators are non-associative, so if count and 1 < x < 10 are rejected. && and || skip the right operand once the left decides; ?: evaluates one branch, and both branches share a type.

open as a page

In Swift, what does `%` return for a negative operand such as `-7 % 3`, and why does `%` not compile on a Double?

level: middleimportance: should knowfreq 35%

basics

~20 s

Swift's % is a remainder, not a modulo: the result takes the left operand's sign, so -7 % 3 is -1, and the divisor's sign is ignored. Double has no %; use truncatingRemainder(dividingBy:) or the IEEE remainder(dividingBy:).

open as a page

A teammate wants `+` on a Swift `Vector2D` struct and a new `•` dot-product operator; how is each declared, and what does a `precedencegroup` decide?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Overloading + needs only a static func + on Vector2D, which keeps AdditionPrecedence. A new • needs a file-scope infix operator declaration naming a precedencegroup, which fixes how tightly it binds against other groups and how a run of it associates.

open as a page

As the lead of a shared Swift codebase, would you allow custom operators, and what rule would you write for when one is acceptable?

level: principalimportance: nice to knowfreq 20%

basics

~20 s

Allow overloading standard operators where the meaning carries over, such as + on vectors or == through Equatable, and keep brand-new operators rare: only for a domain with established notation, each with a named method, an explicit precedencegroup and one owning module.

open as a page