减少,操纵初始值

Reduce, manipulating the initial value

我想用 reduce() 使用另一个数组创建一个数组或字典。通常我会使用:

class Foo {
    var number: Int

    init(number: Int) {
        self.number = number
    }
}

let array1 = [Foo(number: 1), Foo(number: 1), Foo(number: 2)]
let array2: [Int] = array1.reduce([]) { [=10=] + [.number] }

println(array2)

[1, 1, 1]

但是如果我想操纵初始值,我首先必须将它分配给一个新数组,操纵它,然后return那个数组:

let array2: [Int: [Int]] = array1.reduce([:]) {
    var results = [=11=]
    results[.number] = (results[.number] ?? []) + [.number]
    return results
}

println(array2)

[2: [2], 1: [1, 1]]

有没有办法避免必须创建一个新数组并 return 它并直接使用初始值?

您可以在 reduce() 闭包中使参数可变:

let array2: [Int: [Int]] = array1.reduce([:]) {

  (var results, i) in

  results[i.number] = (results[i.number] ?? []) + [i.number]

  return results
}