딕셔너리 (Dictionary)
순서를 정의하지 않고 같은 타입의 key와 같은 타입의 value를 저장
-key는 중복될 수 없다.
-모든 key는 같은 타입이어야 한다.
-모든 value는 같은 타입이어야 한다.
-key 와 value 는 다른 타입이어도 된다.
실물 사전을 찾는 것처럼 순서가 아닌 식별자 기준으로 값을 찾을 때 Dictionary 를 사용함.
자주사용하는 메서드
var namesOfIntegers: [Int: String] = [:]
namesOfIntegers[16] = "sixteen" // 16은 subscript 가 아니라 키 임
//초기화
namesOfIntegers = [:]
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
airports.keys // ["YYZ", "DUB"]
airports.values // ["Toronto Pearson", "Dublin"]
airports.keys.sorted() // ["DUB", "YYZ"]
airports.values.sorted() // ["Dublin", "Toronto Pearson"]
airports["APL"] = "Apple International"
//airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin", "APL": "Apple International"]
//key 에 매칭된 value 값 초기화
airports["APL"] = nil
//딕셔너리 airports 에 있는 값의 수
print(airports.count)
//출력값: 2
//딕셔너리 airports 에 있는 모든 key 들
print(airports.keys)
// ["YYZ", "DUB"]
// 해당 key가 있다면 value를 덮어쓰고, 덮어쓰기 전 기존값을 반환
let newYyz = airports.updateValue("Hello YYZ", forKey: "YYZ")
print(newYyz) // 출력값 : Optional("Toronto Pearson")
print(airports["YYZ"]) // 출력값 : Optional("Hello YYZ")
// 해당 key 가 없다면 그 key 에 해당하는 value 에 값을 추가하고 nil 을 반환
let newApl = airports.updateValue("Hello APL", forKey: "APL")
print(newApl) // 출력값 : nil
print(airports["APL"]) // 출력값 : Optional("Hello APL")