Dictionary (key , value) order

前端 未结 2 1152
一整个雨季
一整个雨季 2021-01-28 03:35

Assume i have the following code

var dictionary = [\"cat\": 2,\"dog\":4,\"snake\":8]; // mutable dictionary
var keys  = dictionary.keys
var values = dictionary.         


        
2条回答
  •  臣服心动
    2021-01-28 03:57

    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> { 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> { 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.

提交回复
热议问题