티스토리 뷰

반응형

 

 


Iterating Over the Contents of  a Dictionary
딕셔너리 컨텐츠 순회탐색하기 

모든 딕셔너리(dictionary)는 정렬되지 않은(unordered) 키-값(key-value) 쌍의 컬렉션으로 되어있습니다.
dictionary또한 Array처럼 for-in 루프를 사용해서 순회할 수 있습니다. for-in 루프 순회 간 딕셔너리의 값을 하나하나 분해해서 key-value 페어 값으로서 요소들을 확인할 수가 있습니다. 

let numberDictionary = ["one": 1, "two": 2, "three": 3]

for (key, value) in numberDictionary {
    print("\(key) is the \(value)")
}

result of print whie iterating dictionary


결과를 보면, 키-값(key-value) 쌍의 순서에는 변함이 없고 안정적이지만, 각 페어 간 순서는 예측할 수 없습니다.

만약 정렬된 상태의 키-값 쌍이 필요하고, Dictinoary에서 제공하는 빠른 키 조회가 필요하지 않다면, KeyValuePairs 타입을 대안으로서 참고 하세요.

 

딕셔너리의 값들을 순회할 때 특정 값만 찾을 수 있도록, 기본 구현에서 제공되는 contains(where:) 이나 firstIndex(where:) 메서드를 사용할 수도 있습니다. 아래의 예시는 각 딕셔너리 페어의 값(value)이 "t" 문자열로 시작하는 첫 인덱스의 값을 출력하는 예시입니다.

let numberDictionary = [1: "one", 2: "two", 3: "three"]

for (key, value) in numberDictionary {
    print("\(key) is the \(value)")
}

let tIndex = numberDictionary.firstIndex(where: { $0.value.hasPrefix("t") })

if let index = tIndex {
    print("first index : \(numberDictionary[index].key) is the \(numberDictionary[index].value)")
} else {
    print("first index : Not Found")
}


해당 예시를 보자면, numberDictionary 딕셔너리에 대해서 기존의 key 접근이 아닌 다른 방법, dictionary index(firstIndex)을 사용하고 있습니다.

key 접근이 옵셔널 타입의 값을 반환했던 반면, index 기반 접근은 그에 대응되는 키-값 페어를 논-옵셔널(non-optional) 튜플 방식으로 반환하게 됩니다. 

위의 예시의 경우, "t"로 시작하는 가장 첫 인덱스의 키-값을 찾아 출력하는 모습입니다. 

 

 

dictionary의 접근 한도

딕셔너리의 색인(indices)는 해당 딕셔너리의 추가된 값들을 저장할 충분한 용량이 있는 한 유효합니다.

만약 dictionary가 가용 버퍼를 초과하게 된다면, 존재하는 색인들이 사전 통지 없이 무효화될 수도 있습니다.

 

let dictionary = [Character: Int](minimumCapacity: 10)

딕셔너리에 얼마나 많이 새로운 값들이 있는지 알고 싶다면, 위와 같이 init(minimumCapacity:) 생성자를 사용해서 정확한 크기의 버퍼를 할당할 수도 있습니다. 

 


 

공식 애플 개발자 문서 [Dictionary] 참고 자료 ▼

 

Dictionary - Swift Standard Library | Apple Developer Documentation

Generic Structure Dictionary A collection whose elements are key-value pairs. Declaration@frozen struct Dictionary where Key : Hashable OverviewA dictionary is a type of hash table, providing fast access to the entries it contains. Each entry in the table

developer.apple.com

 

반응형
댓글
반응형
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함