Sort a Dictionary in Swift

前端 未结 6 1052
情歌与酒
情歌与酒 2020-12-09 11:33

I know that this topic has been already discussed but I can\'t solve looking other answers, so sorry in advance for my ripetion!

I need to sort this Dictionary by ke

6条回答
  •  执笔经年
    2020-12-09 12:13

    Dictionaries are not ordered. If you want to enumerate over them in order, you can do that using @HoaParis's solution (which is my preference), or also

    for (k,v) in sorted(codiceNomeDict, {$0.1 < $1.1}) { ... }
    

    which is just a little better way than what you were doing before because it doesn't generate a temporary array.

    But if you really want "a collection that maps one value to another and is ordered by its key" then you need to create some other data structure for that. So let's do that. It's a good learning experience.

    This version just implements SequenceType and provides a get/set subscript, which is most of what you'd generally want. Making it a full CollectionType is a bit of a pain I think, since startIndex and endIndex hae to be O(1). Possible; just more than I want to do this morning.

    Note the major addition of Key: Comparable. That's why Dictionary can't be ordered. There's no promise that you can sort their keys. By adding that requirement, we can.

    struct SortedDictionary: SequenceType {
        private var dict: Dictionary
        init(_ dict: Dictionary) {
            self.dict = dict
        }
        func generate() -> GeneratorOf<(Key, Value)> {
            let values = Array(zip(self.dict.keys, self.dict.values))
                .sorted {$0.0 < $1.0 }
            return GeneratorOf(values.generate())
        }
        subscript(key: Key) -> Value? {
            get        { return self.dict[key] }
            set(value) { self.dict[key] = value }
        }
    }
    
    var codeValueDict = ["us": "$", "it": "€", "fr": "€"]
    var sortedDict = SortedDictionary(codeValueDict)
    for (k, v) in sortedDict {
        println("\(k) => \(v)")
    }
    sortedDict["us"]
    sortedDict["ab"] = "!"
    sortedDict
    

    Why would you bother with SortedDictionary when you already have sorted()? Well, usually I wouldn't. But it does offer opportunities for abstraction. You could control sort order at object creation rather than at object enumeration. You could potentially cache the sort order (though I suspect in most cases that will hurt rather than help).

    But I recommend just using sorted in general.

提交回复
热议问题