从枚举数组中调用Array.reduce(_:_)

时间:2017-04-03 13:42:20

标签: swift reduce swift3.1 enumerated

正常reduce来电:

[1,2,3].reduce(0, { cur, val in
  return val
})

尝试从reduce调用EnumeratedSequence<Array<Element>>

    [1,2,3].enumerated().reduce(0, { cur, (index, element) in
      return element
    })
  // Error: consecutive statements on a line must be separated by ';'" (at initial reduce closure)

1 个答案:

答案 0 :(得分:2)

您可以使用element访问元组的val.element,使用index访问val.offset

let result = [1,2,3].enumerated().reduce(0, { cur, val in
    return val.element
})

或者,您可以使用赋值来访问元组中的值:

let result = [1,2,3].enumerated().reduce(0, { cur, val in
    let (index, element) = val
    return element
})