swift map reduce 获取下标(index)的方法

前端之家收集整理的这篇文章主要介绍了swift map reduce 获取下标(index)的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原文:http://stackoverflow.com/questions/28012205/map-or-reduce-with-index-in-swift

You can useenumerateto 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"]

Link toenumeratedefinition

Note that this isn't the same as getting theindexof the collection—enumerategives 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.0and.1on the second parameter to yourreduceclosure:

let summedProducts = numbers.enumerate().reduce(0) { (accumulate,current) in
    return accumulate + current.0 * current.1
    //                          ^           ^
    //                        index      element
}
print(summedProducts)   // 56
原文链接:/swift/323450.html

猜你在找的Swift相关文章