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

swift – 在地图上获取下一个值?

发布时间:2020-12-14 04:52:00 所属栏目:百科 来源:网络整理
导读:我正在尝试将元素与集合中的下一个元素进行比较. 例如 : let array: [(Double,String)]= [(2.3,"ok"),(1.4,(5.1,"notOk")] 我需要一个返回的数组,它将汇总字符串相同的元素.所以我的结果将是: new array = [(3.7,"notOk")] 如果可能的话,我需要做它的功能.
我正在尝试将元素与集合中的下一个元素进行比较.

例如 :

let array: [(Double,String)]= [(2.3,"ok"),(1.4,(5.1,"notOk")]

我需要一个返回的数组,它将汇总字符串相同的元素.所以我的结果将是:

new array = [(3.7,"notOk")]

如果可能的话,我需要做它的功能.我试图在地图中获取下一个元素,但无法找到.

像这样的东西(这只是为了逻辑,这段代码不起作用.

let newArray = array.map {(element,nextElement) in 
    if element.1 == nextElement.1 {
        return element.0 + nextElement.0 
    }
}

解决方法

以更实用的方式:

let array: [(Double,"notOk")]
let keys = Set(array.map{$0.1})            // find unique keys
let result = keys.map { key -> (Double,String) in   
    let sum = array.filter {$0.1 == key}   // find all entries with the current key
                   .map {$0.0}             // map them to their values
                   .reduce(0,+)           // sum the values
    return (sum,key)
}
print(result)

输出:

[(5.0999999999999996,“notOk”),(3.6999999999999997,“ok”)]

或者(由@dfri建议):

let keys = Set(array.map{$0.1})            // find unique keys
let result = keys.map { key -> (Double,String) in   
    let sum = array.reduce(0) { $0 + ($1.1 == key ? $1.0 : 0) }
    return (sum,key)
}

(编辑:李大同)

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

    推荐文章
      热点阅读