微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试将元素与集合中的下一个元素进行比较.

例如 :

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)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐