← All lints

same_place_read_write

L0601Correctnesswarn

Right side changes the place it writes

xs[0] = xs.pop()!: the right side changes the place being written

Flagged
var xs: List<Int> = [5, 6, 7]
xs[0] = xs.pop()!
print(xs)
Write instead
var xs: List<Int> = [5, 6, 7]
let last = xs.pop()!
xs[0] = last
print(xs)

Why

xs[0] = xs.pop()! changes xs while it is writing into xs: the pop shortens the list, so whether xs[0] still names the slot you meant depends on the order the two sides run. In C++ the same line is unspecified or undefined. Compute the right side into a let first (let last = xs.pop()!), then assign; the order is then the one you wrote.

The practice it serves

Code that is wrong or almost certainly a bug. Denied by cpl lint.

Not flagged

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

Near miss
var xs: List<Int> = [5, 6, 7]
xs[0] = xs[2]
print(xs)

Turn it off

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

Generated from spec/checker-lints/same_place_read_write, the same record the linter is built from.