【问题标题】:Sort Swift array of dictionaries by value按值对 Swift 字典数组进行排序
【发布时间】:2016-10-14 19:14:13
【问题描述】:

按值对[String : String] 数组进行排序的最佳和最有效的方法是什么?

例如,

let dicts = [["key": "4"], ["key": "4"], ["key": "3"], ["key":"1"]]

然后排序后我想拥有

dicts = [["key": "1"], ["key": "3"], ["key": "4"], ["key":"4"]]

【问题讨论】:

  • @JoshCaswell 你是对的。每个字典中的键名始终相同。我更新了问题。
  • 你可以将每个字典中的值存储为整数而不是字符串吗?

标签: swift sorting dictionary


【解决方案1】:

这有点罗嗦,但它可以让您很好地控制丢失的键和非 int 值。

var array = [["key": "1"], ["key": "3"], ["key": "2"], ["key":"4"]]
array.sort { (lhs, rhs) -> Bool in
    if let leftValue = lhs["key"], let leftInt = Int(leftValue), let rightValue = rhs["key"], let rightInt = Int(rightValue) {
        return leftInt < rightInt
    } else {
        return false // NOTE: you will need to decide how to handle missing keys and non-int values.
    }
}

如果您在比较方面更灵活一些,并且想要更清洁的东西。

array.sort {
    guard let leftValue = $0["key"], let rightValue = $1["key"] else {
        return false // NOTE: you will need to decide how to handle missing keys.
    }

    return leftValue.localizedStandardCompare(rightValue) == .orderedAscending
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 2016-04-17
    • 2015-12-18
    • 2017-01-22
    相关资源
    最近更新 更多