RobertJoseph
RobertJoseph

Reputation: 8158

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)

Upvotes: 1

Views: 713

Answers (1)

vacawama
vacawama

Reputation: 154583

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
})

Upvotes: 5

Related Questions