gpt4 book ai didi

ios - Swift 4 按第一个值排序字典

转载 作者:行者123 更新时间:2023-11-28 11:51:12 25 4
gpt4 key购买 nike

我正在使用 Swift 4 开发一个 iOS 应用程序,我有一个这样的字典:

var list = [
"US" : ["United-States","$"],
"FR" : ["France","€"],
"CN" :["China", "¥"]
]

我想根据每个键的第一个值对基于此字典的 UITableView 进行排序,以获得以下结果:

China
France
United-States

这这可能吗?

最佳答案

您可以获得字典值(数组),映射它们的第一个元素并对其进行排序:

let list = ["US" : ["United-States","$"],
"FR" : ["France","€"],
"CN" : ["China", "¥"]]

let countries = list.values.compactMap{$0.first}.sorted()

print(countries) // ["China", "France", "United-States"]

另一种选择是为您的货币创建一个结构,创建一个采用键值对并使其符合 Comparable 协议(protocol)的自定义初始化程序:

struct Currency: CustomStringConvertible, Comparable {
let name: String
let code: String
let symbol: String
init?(currency: (key: String, value: [String])) {
guard currency.value.count == 2 else { return nil }
self.code = currency.key
self.name = currency.value.first!
self.symbol = currency.value.last!
}

var description: String {
return "Code: \(code)\nName: \(name)\nSynmbol: \(symbol)\n"
}
}
extension Currency {
static func <(lhs: Currency, rhs: Currency) -> Bool {
return lhs.name < rhs.name
}
}

let list = ["US" : ["United-States","$"],
"FR" : ["France","€"],
"CN" :["China", "¥"]]

let currencies = list.compactMap(Currency.init).sorted()
currencies.map({print($0)})

这将打印:

Code: CN

Name: China

Synmbol: ¥

Code: FR

Name: France

Synmbol: €

Code: US

Name: United-States

Synmbol: $

关于ios - Swift 4 按第一个值排序字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51886161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com