从枚举数组调用 Array.reduce(_:_)
Call Array.reduce(_:_) from enumerated array
正常reduce
通话:
[1,2,3].reduce(0, { cur, val in
return val
})
尝试从 EnumeratedSequence<Array<Element>>
调用 reduce
:
[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)
您可以使用 val.element
访问元组的 element
并使用 val.offset
:
访问 index
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
})
正常reduce
通话:
[1,2,3].reduce(0, { cur, val in
return val
})
尝试从 EnumeratedSequence<Array<Element>>
调用 reduce
:
[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)
您可以使用 val.element
访问元组的 element
并使用 val.offset
:
index
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
})