FlatMap Over Map Reduce

ID

swift.flatmap_over_map_reduce

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Swift

Tags

efficiency, idiomatic

Description

Reports the .map(…​).reduce([], +) chain. .flatMap(…​) is equivalent and runs in a single pass.

nodes.map { $0.children }.reduce([], +)     // FLAW
nodes.flatMap { $0.children }               // OK

Rationale

.map(…​).reduce([], +) builds an intermediate , then concatenates the inner arrays one at a time. Array concatenation copies both operands, so the whole pipeline is O(n²) in the total element count. flatMap walks the input once and appends to a single output array — O(n).

Remediation

Replace the chain with flatMap:

let allChildren = nodes.flatMap { $0.children }

The rule only matches the exact (empty-array, +) reduce shape, so it leaves alone reductions into scalars (.reduce(0, +)) and non-empty initial values.