Swift - Stored values order is completely changed in Dictionary

徘徊边缘 提交于 2019-11-26 12:31:06

This is because of the definition of Dictionaries:

Dictionary

A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.

There is no order, they might come out differently than they were put in.
This is comparable to NSSet.


Edit:

NSDictionary

Dictionaries Collect Key-Value Pairs. Rather than simply maintaining an ordered or unordered collection of objects, an NSDictionary stores objects against given keys, which can then be used for retrieval.

There is also no order, however there is sorting on print for debugging purposes.

You can't sort a dictionary but you can sort its keys and loop through them as follow:

let myDictionary = ["name1" : "Loy", "name2" : "Roy", "name3" : "Tim", "name4" : "Steve"]   // ["name1": "Loy", "name2": "Roy", "name3": "Tim", "name4": "Steve"]


let sorted = myDictionary.sorted {$0.key < $1.key}  // or {$0.value < $1.value} to sort using the dictionary values
print(sorted) // "[(key: "name1", value: "Loy"), (key: "name2", value: "Roy"), (key: "name3", value: "Tim"), (key: "name4", value: "Steve")]\n"
for element in sorted {
    print("Key = \(element.key) Value = \(element.value)" )
}

Neither NSDictionary nor Swift::Dictionary orders its storage. The difference is that some NSDictionary objects sort their output when printing and Swift::Dictionary does not.

From the documentation of -[NSDictionary description]:

If each key in the dictionary is an NSString object, the entries are listed in ascending order by key, otherwise the order in which the entries are listed is undefined. This property is intended to produce readable output for debugging purposes, not for serializing data.

From The Swift Programming Language:

A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.

Basically, order of items as seen in output is arbitrary, dependant on internal implementation of data structure, and should not be relied on.

This is indeed an issue with dictionaries. However, there's a library available to make sure the order stays the way you initialised it.

OrderedDictionary is a lightweight implementation of an ordered dictionary data structure in Swift.

The OrderedDictionary structure is an immutable generic collection which combines the features of Dictionary and Array from the Swift standard library. Like Dictionary it stores key-value pairs and maps each key to a value. Like Array it stores those pairs sorted and accessible by a zero-based integer index.

Check it out here: https://github.com/lukaskubanek/OrderedDictionary

A little late for the party but if you want to maintain the order then use KeyValuePairs, the trade-off here is that if you use KeyValuePairs you lose the capability of maintaining unique elements in your list

var user: KeyValuePairs<String, String> {
    return ["FirstName": "NSDumb",
            "Address": "some address value here",
            "Age":"30"]
}

prints

["FirstName": "NSDumb", "Address": "some address value", "Age": "30"]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!