减少,操纵初始值

时间:2015-05-21 00:09:13

标签: arrays swift reduce

我想使用另一个数组创建一个带有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([]) { $0 + [$1.number] }

println(array2)

[1, 1, 1]

但是如果我想操纵初始值,我首先必须将它分配给一个新数组,操纵它并返回该数组:

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

println(array2)

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

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

1 个答案:

答案 0 :(得分:0)

您可以在reduce()闭包中创建参数变量:

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

  (var results, i) in

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

  return results
}