← All lints

char_offset_index

L0574Idiomswarn

Letter offset as an index

cnt[c - 'a']: index by a domain Letter = 'a'..='z' instead

Flagged
let s = "abca"
var cnt: [0..26]Int = 0
for c in s:
    cnt[c - 'a'] += 1
print(cnt[0])
Write instead
domain Letter = 'a'..='z'
let s = "abca"
var cnt: [Letter]Int = 0
for c in s:
    cnt[Letter(c)] += 1
print(cnt[Letter('a')])

Why

cnt[c - 'a'] is C++'s letter table: the letters become Int offsets, so [0..26]Int accepts any number and an uppercase letter or a digit silently lands on the wrong cell or traps far from the read. domain Letter = 'a'..='z' names the index space once: [Letter]Int has one cell per letter, cnt[Letter(c)] says which, and a character outside 'a'..='z' traps where it enters with its value. Prints and loops then read cnt[Letter('a')] and for l in Letter.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.strings.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let s = "abca"
let a = [1, 2, 3]
for c in s:
    print(c - 'a', a[c.ord % 3])

Turn it off

For one block, wrap it in with lint(char_offset_index: allow):. For a project, add char_offset_index = "allow" under [lints] in cp.toml.

Generated from spec/lints/char_offset_index, the same record the linter is built from.