Swift中reduce(into:)用法疑问:代码逻辑解析求助
reduce(into:) in Your Odd/Even Array Split Code Hey, let's break this down step by step — I remember being confused by reduce(into:) at first too, so I get where you're coming from! Let's unpack every part of that code to make it crystal clear.
First, Recap What reduce(into:) Does
Unlike the standard reduce(_:_:), which creates a new copy of the accumulator each iteration, reduce(into:) lets you directly modify the initial accumulator you pass in. This makes it way more efficient, especially for mutable types like arrays.
Let's look at your code again to map each piece:
let nums = [1,2,3,4,5] let result = nums.reduce(into: [[],[]]) { temp, i in temp[i%2].append(i) } // Result: [[2,4],[1,3,5]]
Breaking Down the Closure Components
Let's go line by line inside that closure:
1. The temp Parameter
temp is just a reference to the initial accumulator you passed in: [[],[]] (an array holding two empty arrays). Every time we loop through an element in nums, we're modifying this same temp array directly — no new copies are made here (that's the "into" magic!).
2. The i Parameter
i is the current element from the nums array we're iterating over. For example:
- First loop:
i = 1 - Second loop:
i = 2 - ... and so on until
i = 5
3. The in Keyword
This is just Swift closure syntax sugar — it separates the closure's parameter list (here, temp, i) from the actual code that runs inside the closure. Think of it as saying: "Given these parameters, run the code that follows."
The Core Logic: temp[i%2].append(i)
This is where the splitting happens, let's break it down:
i%2calculates the remainder wheniis divided by 2. For any integer, this will be 0 if even, 1 if odd.temp[i%2]accesses either the first (temp[0]) or second (temp[1]) sub-array in our accumulator:- When
iis even (2,4),i%2 = 0→ we append totemp[0] - When
iis odd (1,3,5),i%2 = 1→ we append totemp[1]
- When
append(i)adds the current element to the selected sub-array.
By the time all elements are processed, temp has been modified to hold all evens in the first sub-array and odds in the second — which becomes our final result.
Quick Comparison to Standard reduce
Just to highlight the difference, here's how you'd write the same logic with standard reduce (notice we have to create and return a new array each time, which is less efficient):
let result = nums.reduce([[],[]]) { acc, i in var newAcc = acc newAcc[i%2].append(i) return newAcc }
reduce(into:) saves us from these unnecessary copies, which is why it's the better choice here.
内容的提问来源于stack exchange,提问作者Massimiliano Bartolini

