原文:http://stackoverflow.com/questions/28012205/map-or-reduce-with-index-in-swift
You can useenumerate
to convert a sequence (Array
,String
,etc.) to a sequence of tuples with an integer counter and and element paired together. That is:
let numbers = [7,8,9,10] let indexAndNum: [String] = numbers.enumerate().map { (index,element) in return "\(index): \(element)" } print(indexAndNum) // ["0: 7","1: 8","2: 9","3: 10"]
Note that this isn't the same as getting theindexof the collection—enumerate
gives you back an integer counter. This is the same as the index for an array,but on a string or dictionary won't be very useful. To get the actual index along with each element,you can usezip
:
let actualIndexAndNum: [String] = zip(numbers.indices,numbers).map { "\($0): \($1)" } print(actualIndexAndNum) // ["0: 7",sans-serif"> When using an enumerated sequence withreduce
,you won't be able to separate the index and element in a tuple,since you already have the accumulating/current tuple in the method signature. Instead,you'll need to use.0
and.1
on the second parameter to yourreduce
closure:let summedProducts = numbers.enumerate().reduce(0) { (accumulate,current) in return accumulate + current.0 * current.1 // ^ ^ // index element } print(summedProducts) // 56原文链接:/swift/323450.html