Search code examples
swiftreduceswift3enumerated

Call Array.reduce(_:_) from enumerated array


Normal reduce call:

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

Attempt at calling reduce from an 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)

Solution

  • You can access the element of the tuple with val.element and the index with val.offset:

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

    Alternatively, you can use assignment to access the values in the tuple:

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