2014-12-08 72 views
0

假设我有以下代码词典(键,值)顺序

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是“狗“,”蛇“,”猫“ 将dictionary.values总是4,8,2? 我在操场上试过它,结果总是表示它们具有相同的顺序

回答

4

不,它不保证是在相同的顺序。从文档:

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

+0

这是真的。虽然经验表明它们以简单测试的相同顺序出现,但不能保证。如果您需要某个订单,请为这些密钥使用单独的数组。 – 2014-12-08 08:33:20

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 } 

钥匙的解释/值出现在为相同的顺序他们作为/.1成员 键值对在self

dictionary.keysdictionary.values返回键和值在 “匹配”的顺序。

那么字典的键值对没有特定的顺序,不过 第一,第二,...的dictionary.values 元素是对应于第一,第二,...元素的字典值dictionary.keys