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

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

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

Link to enumerate
definition

Note that this isn't the same as getting the index of 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 use zip:

let actualIndexAndNum: [String] = zip(numbers.indices, numbers).map { 
    "\($0): \($1)"
 }
print(actualIndexAndNum)// ["0: 7", "1: 8", "2: 9", "3: 10"]

When using an enumerated sequence with reduce
, 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 your reduce
closure:

let summedProducts = numbers.enumerate().reduce(0)
 { (accumulate, current) in 
    return accumulate + current.0 * current.1
     //                         ^           ^ 
    //                        index      element
}
print(summedProducts) // 56
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,567评论 5 6
  • 第一轮:皮筋拉锯战。不知何时皮筋成了小人们的最爱,那种小小的彩色圈圈,开始时只是偶尔几个玩玩,提醒不要影响上课,注...
    疏影欣雨阅读 443评论 0 0
  • 1、class 和 id 的使用场景? class 匹配class包含特定类的元素,比如说页面有些元素有共同的特征...
    饥人谷_醉眼天涯阅读 178评论 0 0
  • 累,甚至疼痛,都可以熬过去。怕就怕,对方一点都看不见。原来,失望到了一定程度,真的是不愿多说,不愿沟通。前方的路,...
    小地主麻麻阅读 217评论 0 0
  • 昨夜,我在脑海写了几句无头无尾的诗 我发现比以往的都好,隐喻深刻,饱满有力 但没有一首属于完整,残缺并不是美,是真...
    崇文路2号阅读 218评论 0 0