Sort a Dictionary in Swift

前端 未结 6 1070
情歌与酒
情歌与酒 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:16

    Swift doesn't include a sorted dictionary type, and dictionaries cannot be sorted. You could add an extension that offers sorting to [(Key, Value)] by doing this:

    extension Dictionary {
    
        func sort(isOrderedBefore: (Key, Key) -> Bool) -> [(Key, Value)] {
            var result: [(Key, Value)] = []
            let sortedKeys = keys.array.sorted(isOrderedBefore)
            for key in sortedKeys {
                result.append(key, self[key]!)
            }
            return result
        }
    }
    

提交回复
热议问题