加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:52:57 所属栏目:百科 来源:网络整理
导读:原文: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

原文: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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读