Array Subscript Zero
ID |
swift.array_subscript_zero |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Swift |
Tags |
collections, reliability |
Description
Reports a subscript expression of the form <expr>[0]. For arrays,
prefer .first — it returns an Optional, so accessing the head of an
empty collection produces nil instead of crashing.
let head = xs[0] // FLAW
let nested = xs[0][0] // FLAW (two)
if let head = xs.first { ... } // OK
print(xs[1]) // OK — non-zero literal
print(xs[xs.count - 1]) // OK — non-literal
print(xs[0..<2]) // OK — range subscript
Rationale
array[0] traps at runtime if the array is empty. .first returns
Optional.none and lets callers decide how to handle the empty case.
Remediation
Use .first and unwrap with if let or guard let:
guard let head = xs.first else {
return
}
process(head)