简体   繁体   English

Swift 4按第一个值排序字典

[英]Swift 4 sort dictionary by the first value

I'm working on an iOS app using Swift 4 and I have a dictionary like this: 我正在使用Swift 4开发iOS应用,并且有这样的字典:

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

I would like to sort a UITableView based on this dictionary by the first value of each key in order to get the following result: 我想根据每个字典的第一个值对基于此字典的UITableView进行排序,以获得以下结果:

China
France
United-States

This this possible? 这可能吗?

You can get your dictionary values (arrays), map their first element and sort it: 您可以获取字典值(数组),映射它们的第一个元素并对其进行排序:

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

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

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

Another options is to create a struct for your currency, create a custom initializer that takes a key value pair and make it conform to Comparable protocol: 另一个选择是为您的货币创建一个结构,创建一个采用键值对并使其符合Comparable协议的自定义初始化程序:

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

This will print: 这将打印:

Code: CN 代码:CN

Name: China 名称:中国

Synmbol: ¥ 语法:¥

Code: FR 代号:FR

Name: France 名称:法国

Synmbol: € 语法:€

Code: US 代码:美国

Name: United-States 名称:美国

Synmbol: $ 语法:$

Use map to create an array of tuples with your country's symbol , name , and currency , and then sort that array by name : 使用map创建具有您国家的symbolnamecurrency的元组数组,然后按name对该数组进行排序:

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

let newlist = list.map { (symbol: $0.key, name: $0.value.first ?? "", currency: $0.value.dropFirst().first ?? "")}.sorted { $0.name < $1.name }

print(newlist)

[(symbol: "CN", name: "China", currency: "¥"), (symbol: "FR", name: "France", currency: "€"), (symbol: "US", name: "United-States", currency: "$")] [(符号:“ CN”,名称:“ China”,货币:“¥”),(符号:“ FR”,名称:“ France”,货币:“€”),(符号:“ US”,名称: “美国”,货币:“ $”)]

This will allow you to access all of the information easily for your table: 这将使您轻松访问表的所有信息:

let symbol = newlist[indexPath.row].symbol
let name = newlist[indexPath.row].name
let currency = newlist[indexPath.row].currency

or just: 要不就:

let (symbol, name, currency) = newlist[indexPath.row]

For your more complicated dictionary... 对于更复杂的字典...

One of your problems is that your value is now [Any] , so conditional casts are needed. 您的问题之一是您的value现在是[Any] ,因此需要有条件的强制转换。 Also, break up creation of the newlist and the sorting. 此外,向上突破的创作newlist和排序。

let list = ["US" : ["United-States","$","My comment", 10],
            "FR" : ["France","€", "My super comment", 20],
            "CA" : ["Canada","$", "Whatever", 15],
            "CN" : ["China", "¥", "Final comment", 5]]

let newlist = list.map { (symbol: $0.key,
                          name: $0.value.first as? String ?? "",
                          currency: $0.value.dropFirst().first as? String ?? "",
                          comment: $0.value.dropFirst(2).first as? String ?? "",
                          value: $0.value.dropFirst(3).first as? Int ?? 0) }

let sortedlist = newlist.sorted { $0.name < $1.name }
print(sortedlist)

[(symbol: "CA", name: "Canada", currency: "$", comment: "Whatever", value: 15), (symbol: "CN", name: "China", currency: "¥", comment: "Final comment", value: 5), (symbol: "FR", name: "France", currency: "€", comment: "My super comment", value: 20), (symbol: "US", name: "United-States", currency: "$", comment: "My comment", value: 10)] [(符号:“ CA”,名称:“ Canada”,货币:“ $”,注释:“ Whatever”,值:15),(符号:“ CN”,名称:“ China”,货币:“¥”,评论:“最终评论”,价值:5),(符号:“ FR”,名称:“法国”,货币:“€”,评论:“我的超级评论”,价值:20),(符号:“美国” ,名称:“美国”,货币:“ $”,评论:“我的评论”,值:10)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM