swift map reduce 獲取下標(biāo)(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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,667評論 5 6
  • 第一輪:皮筋拉鋸戰(zhàn)。不知何時皮筋成了小人們的最愛,那種小小的彩色圈圈,開始時只是偶爾幾個玩玩,提醒不要影響上課,注...
    疏影欣雨閱讀 472評論 0 0
  • 1、class 和 id 的使用場景? class 匹配class包含特定類的元素,比如說頁面有些元素有共同的特征...
    饑人谷_醉眼天涯閱讀 208評論 0 0
  • 累,甚至疼痛,都可以熬過去。怕就怕,對方一點(diǎn)都看不見。原來,失望到了一定程度,真的是不愿多說,不愿溝通。前方的路,...
    小地主麻麻閱讀 228評論 0 0
  • 昨夜,我在腦海寫了幾句無頭無尾的詩 我發(fā)現(xiàn)比以往的都好,隱喻深刻,飽滿有力 但沒有一首屬于完整,殘缺并不是美,是真...
    崇文路2號閱讀 247評論 0 0

友情鏈接更多精彩內(nèi)容