Dictionary Reference
Swift 표준 라이브러리 문서에서 일부 번역했습니다. 원본주소:https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/Dictionary.html#//apple_ref/doc/uid/TP40014608-CH4-SW1
타입 선언
Dictionary<KeyType, ValueType>
과 같이 선언하며 보통은
[Keytype:ValueType]
으로도 쓴다.
init(minimumCapacity: =2)
빈 사전을 만든다.
init(minimumCapacity: Int = 2)
즉, 디폴트 파라미터에 의해서 새롭게 생성되는 빈 사전은 최소 2개의 키-값 쌍을 저장ㅇ할 내부 버퍼를 갖는다.
var emptyDictionary = Dictionary<String, Int>()
같은 방식으로
var equivalentEmptyDictionary = [String:Int]()
subscript(KeyType) -> ValueType? {get set}
사전의 subscript는 옵셔널 타입을 리턴한다.
subscript(key: KeyType) -> ValueType? { get{} set{} }
따라서 사용할 때는 반드시 nil 검사를 해야 한다.
if let unwrappedValue = dict["three"] {
println("The integer value for \"three\" was: \(unwrappedValue)")
}
값을 nil로 변경하면 해당 키가 제거된다.
var dict = ["one":1, "two":2, "three":3, "four":4]
dict["three"] = nil
// dict == ["one":1, "two":2, "four":4]
updateValue(\_:, forKey:) -> ValueType?
키 값을 업데이트한다. 대신 이전 키 값이 있으면 리턴해준다.
mutating func updateValue(value: ValueType, forKey: KeyType) -> ValueType?
removeValueForKey(\_:) -> ValueType?
마찬가지로 키-값 쌍을 제거하는데, 제거되는 값을 리턴해준다.
mutating func removeValueForKey(key: KeyType) -> ValueType?
removeAll(keepCapacity:=false)
모든 키-값 쌍을 제거한다. 기본적으로 keepCapacity
값이 false이면 저장 버퍼도 비워진다.
var count {get}
키-값 쌍의 개수
var count:Int { get{}}
var keys { get }
키들의 이터레이터를 리턴한다.
var keys:MapCollectionView<Dictionary<KeyType, ValueType>, KeyType> { get }
이는 이터레이터로 for .. in 문에 그대로 사용할 수 있다. 단, 배열로 활용하려면 배열로 만들어 주어야 한다.
var dictionary = ["one":1, "two":2, "three":3]
for key in dictionary.keys {
println("key: \(key)")
}
let array = Array(dictionary.keys)
var values { get }
값들을 이터레이터로 리턴한다. 순서는 랜덤
var values:MapCollectionView<Dictionary<KeyType, ValueType>, ValueType> { get }
==
두 사전이 같은 키-값 쌍들을 가지고 있는지 검사
!=
==
가 아닌지 검사.