字典(键,值)顺序

时间:2014-12-08 07:39:12

标签: ios swift dictionary

假设我有以下代码

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)
}

dictionary.keys和dictionary.values的顺序是否相同

例如,如果dictionary.keys是" dog"," snake"," cat" dictionary.values总是4,8,2? 我在操场上试了一下,结果总是表明他们有相同的顺序

2 个答案:

答案 0 :(得分:4)

不,不能保证按相同的顺序排列。来自文档:

  

Swift的Dictionary类型是一个无序集合。顺序在哪   迭代时,检索键,值和键值对   字典未指定。

答案 1 :(得分:1)

keysvalues属性的定义前面有以下内容 注释:

/// 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 }

我对

的解释
  

键/值以与.0 / .1成员相同的顺序出现   self中的键值对。

dictionary.keysdictionary.values返回键和值 “匹配”订单。

因此字典的键值对没有指定的顺序,但是 dictionary.values的第一个,第二个......元素 是与dictionary.keys的第一个,第二个......元素对应的字典值。