You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中reduce(into:)用法疑问:代码逻辑解析求助

Understanding 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%2 calculates the remainder when i is 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 i is even (2,4), i%2 = 0 → we append to temp[0]
    • When i is odd (1,3,5), i%2 = 1 → we append to temp[1]
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 19:22:58