简体   繁体   English

你如何在 swift 中使用 reduce(into:)

[英]How do you use reduce(into:) in swift

I am reading iOS 13 Programming Fundamentals with Swift, got to the part about reduce() and I think I understand it more or less, but then there is reduce(into:) and this piece of code:我正在阅读 iOS 13 Programming Fundamentals with Swift,到了关于 reduce() 的部分,我想我或多或少地理解了它,但是还有 reduce(into:) 和这段代码:

let nums = [1,2,3,4,5]
let result = nums.reduce(into: [[],[]]) { temp, i in 
    temp[i%2].append(i)
}
// result is now [[2,4],[1,3,5]]

So this code takes an array of Int and splits it into 2 arrays, even and odd.所以这段代码需要一个 Int 数组并将其分成 2 个 arrays,偶数和奇数。 The problem is that I have no idea what's happening inside the brackets {}.问题是我不知道括号 {} 内发生了什么。

In the case of reduce, the first parameter is the first one of the iteration and then the closure is supposed to process all the items one after the other, similar to map() but more powerful (here one loop is enough to get the two arrays but with map() I would need 2 loops, according to the book).在reduce的情况下,第一个参数是迭代的第一个参数,然后闭包应该一个接一个地处理所有的项目,类似于map()但更强大(这里一个循环足以得到两个arrays 但使用 map() 我需要 2 个循环,根据书)。

I cannot understand the syntax here anyway, especially what does "temp" stand for and that use of "in".无论如何,我无法理解这里的语法,尤其是“temp”代表什么以及“in”的使用。 And how is "append()" appending the value to the proper array??以及“append()”如何将值附加到正确的数组?

Inside the closure, "temp" is the result format which is [[][]] and "i" is each number.在闭包内部,“temp”是结果格式,即 [[][]],“i”是每个数字。 As you said it processes all numbers in a loop.正如您所说,它会循环处理所有数字。 When % is used it returns the division remainder, so for the odd numbers like "1,3,5", it returns "1" and for the even numbers "0", which means that "temp" appends these values to the array in these respective indexes.当使用 % 时,它返回除法余数,因此对于像“1,3,5”这样的奇数,它返回“1”,对于偶数“0”,这意味着“temp”将这些值附加到数组中在这些各自的索引中。

So if we debug and replace the variables for constants the results would be:因此,如果我们调试并替换常量的变量,结果将是:

temp[1].append(1) //1%2 = 1/2 left 1 [[][1]]
temp[0].append(2) //2%2 = 2/2 left 0 [[2][1]]
temp[1].append(3) //3%2 = 3/2 = 1 left 1 [[2][1,3]]
temp[0].append(4) //4%2 = 4/2 left 0 [[2,4][1,3]]
temp[1].append(5) //5%2 = 5/2 = 2 left 1 [[2,4][1,3,5]]

According to the documentation the closure is called sequentially with a mutable accumulating value initialized that when exhausted, is returned to the caller.根据文档,闭包被顺序调用,可变的累积值初始化,当用尽时,返回给调用者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM