Dictionary (key , value) order

Assume i have the following code

var dictionary = ["cat": 2,"dog":4,"snake":8]; // mutable dictionary
var keys  = dictionary.keys
var values = dictionary.values
for e in keys {
    println(e)
}
for v in values {
    println(v)
}

would the dictionary.keys and dictionary.values have the same order

  • Check direction of scroll in UIScrollView
  • How can Create Model class in swift and get values form model class in another class
  • How To Use AVCaptureStillImageOutput To Take Picture
  • Force iOS view to not rotate, while still allowing child to rotate
  • set a delegate for UIWebView
  • Why does my UIImage take up so much memory?
  • for example if the dictionary.keys is “dog”,”snake”,”cat”
    would the dictionary.values be always 4,8,2?
    i tried it on the playground and the result always indicated that they have the same order

    2 Solutions Collect From Internet About “Dictionary (key , value) order”

    No, it is not guaranteed to be in the same order. From documentation:

    Swift’s Dictionary type is an unordered collection. The order in which
    keys, values, and key-value pairs are retrieved when iterating over a
    dictionary is not specified.

    The definition of the keys and values property is preceded by the following
    comments:

    /// A collection containing just the keys of `self`
    ///
    /// Keys appear in the same order as they occur as the `.0` member
    /// of key-value pairs in `self`.  Each key in the result has a
    /// unique value.
    var keys: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Key>> { get }
    
    /// A collection containing just the values of `self`
    ///
    /// Values appear in the same order as they occur as the `.1` member
    /// of key-value pairs in `self`.
    var values: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Value>> { get }
    

    My interpretation of

    Keys/Values appear in the same order as they occur as the .0/.1 member of
    key-value pairs in self.

    is that dictionary.keys and dictionary.values return the keys and values in
    “matching” order.

    So the key-value pairs of a dictionary do not have a specified order, but
    the first, second, … element of dictionary.values
    is the dictionary value corresponding to the first, second, … element of dictionary.keys.