2014-12-08 4 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인지를했을 다음 코드가 가정 "개 ","snake ","cat " dictionary.values는 항상 4,8,2가 될까요? 나는 놀이터에서 그걸 시도해 보았는데 결과가 항상 같은 주문임을 나타냈다.

답변

4

아니요, 같은 순서가 아니어도 괜찮습니다. 문서에서 :

스위프트의 사전 형식은 정렬되지 않은 모음입니다. 사전을 반복 할 때 키, 값 및 키 - 값 쌍이 검색되는 순서는 지정되지 않습니다.

+0

사실입니다. 경험상 간단한 테스트를 위해 같은 순서로 나타나지만 경험에 대한 보장은 없습니다. 특정 순서가 필요한 경우 키에 대해 별도의 배열을 사용하십시오. –

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 구성원이 키 - 값 쌍인 경우 발생합니다..

dictionary.keys이고 "일치"순서로 키 값을 반환 dictionary.values.

그래서 사전의 키 - 값 쌍은 특정한 순서를 가지고 있지만 하지 않은 제 1, 제 2, ..., dictionary.values 의 소자의 제 1, 제 2, ..., 요소에 대응하는 사전 값은 dictionary.keys.