As Marco我想说一个字典可能是更好的数据结构使用,但如果你坚持保存在一个元组数组中,你可以使用一些更高阶的函数疯狂,Swift 2(为什么你会用1.2?):
let array = [(2014,3),(2014,2),(2014,6),(2015,8),(2015,5)]
let keys = Set(array.map{return $0.0})
let result = keys.map{(k:Int) -> (Int,Int) in (k, array.filter{ $0.0 == k }.map{ $0.1 }.reduce(0, combine:+))}
print(result)
结果
[(2014, 11), (2015, 13)]
注意到,一组不保证其内容的顺序。实际上它没有秩序。 为了确保您可以使用sort{$0.0 < $1.0}
let result = keys.map{(k:Int) -> (Int,Int) in (k, array.filter{ $0.0 == k }.map{ $0.1 }.reduce(0, combine:+))}.sort{$0.0 < $1.0}
一个优点在字典中的解决方案是排序的功能顺序。
let result = ....sort{$0.0 < $1.0}
- >[(2014, 11), (2015, 13)]
let result = ....sort{$0.0 > $1.0}
- >[(2015, 13), (2014, 11)]
let result = ....sort{$0.1 > $1.1}
- >[(2015, 13), (2014, 11)]
let result = ....sort{$0.1 < $1.1}
- >[(2014, 11), (2015, 13)]
该代码甚至没有编译... –
这是一种大学任务吗?如果代码至少可以做某些事情,它可以帮助获得更好的答案。 – courteouselk