如何使用最高的Int值对字典进行排序或过滤?

时间:2017-01-25 21:51:33

标签: arrays swift sorting

我有一组元组,

var basics = [String: Int]()
basics = ["harry": 89, "chris": 33, "jane": 98, "hans": 90, "finn": 98 ]

我如何对数组进行排序或过滤以获得具有最高值的元组,考虑可能有多个的情况,如上所述" jane"和"芬恩"两者都有98?

2 个答案:

答案 0 :(得分:3)

您可以通过排序然后过滤列表来获得此信息。为此,您将使用Swift的一些标准高级函数:

//define basics
let basics = ["harry": 89, "chris": 33, "jane": 98, "hans": 90, "finn": 98 ]
//sort basics by the age value from highest to lowest
let sortedBasics = basics.sorted { $0.value > $1.value }
//filter the list to remove any elements with a value lower than our recorded high
let filteredBasics = sortedBasics.filter { $1 == sortedBasics.first?.value }
print(filteredBasics) //[("jane", 98), ("finn", 98)]

供参考:$0$1被视为filtersorted函数的推断参数的“简写”名称。另请注意,这两个函数不会发生变异,因此basics仍处于相同状态。

答案 1 :(得分:0)

extension Dictionary where Value : Comparable, Value : Hashable {

    public func maxKeys() -> (max: Value?, keys: [Key]) {
        guard count > 0 else {
            return (nil, [])
        }

        var max: Value = first!.value
        var keys: [Key] = []

        for (key, value) in self {
            if value > max {
                max = value
                keys = [key]
            } else if value == max {
                keys.append(key)
            }
        }

        return (max, keys)
    }

}

let (max, keys) = basics.maxKeys()

print(max!, keys)
// 98 ["jane", "finn"]