dictonary는 같은 타입의 key들과 같은 타입의 value들의 조합을 순서 없이 저장한다.
각각의 value들은 유니크한 key들과 연관되어 있는데. key를 사용하여 dictonary에 특정 value들이 있는지를 판단할 수 있다.
array와는 다르게 dictonary안의 아이템들은 특정한 순서가 없다.
dictionary는 현실의 사전처럼 특정한 key에 어떠한 value가 있는지를 알고싶을 때 사용한다.
Swift에서 dictonary는 Dictionary<Key, Value>와 같이 타입을 지정한다.
[Key:Value] 와 같이 축약하여 표현도 가능하다.
array처럼 빈 dictonary를 만들 수 있다.
var namesOfIntegers: [Int: String] = [:]
// namesOfIntegers 는 [Int: String]타입의 빈 dictionary 이다.
dictonary 또한 array 처럼 Dictonary Literal을 사용하여 생성할 수 있다.
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
dictonary인 airports는 타입이 [String: String]으로 생성되었기 때문에 key와 value 모두 String 타입의 값이 와야한다.
읽기 전용 프로퍼티인 count를 사용해 dictonary안에 몇개의 아이템들이 있는지 알 수 있다.
print("The airports dictionary contains \(airports.count) items.")
// "The airports dictionary contains 2 items." 출력
isEmtpy 프로퍼티를 사용해 dictonary가 비었는지(== count의 값이 0인지)를 알 수 있다.
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary isn't empty.")
}
// "The airports dictionary isn't empty." 출력
subscript syntax를 사용해 새로운 item을 dictonary에 넣을 수 있다.
airports["LHR"] = "London"
// airports dictionary는 3개의 아이템을 가지고 있다.
subscript syntax를 사용하여 특정 key에 해당하는 value를 바꿀 수 있다.
airports["LHR"] = "London Heathrow"
// key "LHR" 에 해당하는 값 "London" 은 "London Heathrow" 으로 바뀌었다.
dictonary의 updateValue(_:forKey:) 메소드를 사용해 해당하는 key에 대한 value를 설정하거나 바꿀 수 있다. 해당하는 key가 없다면 새로운 item이 추가되고, 이미 존재한다면 key에 해당하는 value의 값이 바뀐다.
updateValue 메소드는 바뀌기 전의 값을 반환하는데, 이를 사용해 값의 변화가 일어났는지를 체크할 수 있다. 만약 해당하는 key가 없어 새롭게 아이템이 추가됐다면 updateValue 메소드는 nil을 반환한다.
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
// "The old value for DUB was Dublin." 출력
subscript syntax를 사용해 dictonary에 특정 key에 해당하는 value를 얻을 수 있는데. 이 경우 특정 key가 존재하지 않을 수 있기 때문에 optional 한 value에 해당하는 타입을 반환한다.
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport isn't in the airports dictionary.")
}
// "The name of the airport is Dublin Airport." 출력
subscript syntax를 사용해 key-value쌍을 지울수도 있는데, value에 nil의 값을 할당하면 지워진다.
airports["APL"] = "Apple International"
airports["APL"] = nil
// APL은 dictionary에서 지워진다.
removeValue(forKey:) 메소드를 사용해 지울수도 있다. 이 메소드는 지워진 value를 반환하며, 존재하지 않는 key를 지우려하면 nil을 반환한다.
if let removedValue = airports.removeValue(forKey: "DUB") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary doesn't contain a value for DUB.")
}
// "The removed airport's name is Dublin Airport." 출력
for-in 루프를 사용해 key-value 쌍을 순회할 수 있다. dictonary의 각 item들은 (key, value) 형식의 튜플의 형태로 반환된다.
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
// LHR: London Heathrow
// YYZ: Toronto Pearson
keys, values 프로퍼티를 사용해 dictonary의 key와 value를 순회할 수 있다.
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
// Airport code: LHR
// Airport code: YYZ
for airportName in airports.values {
print("Airport name: \(airportName)")
}
// Airport name: London Heathrow
// Airport name: Toronto Pearson
keys와 values 프로퍼티를 사용하면 해당하는 타입의 array를 반환한다.
let airportCodes = [String](airports.keys)
// airportCodes is ["LHR", "YYZ"]
let airportNames = [String](airports.values)
// airportNames is ["London Heathrow", "Toronto Pearson"]
Swift의 dictonary는 순서가 정의되어 있지 않기 때문에 keys와 values를 특정한 순서로 순회하고 싶다면 sorted 메소드를 사용해 정렬한 후 순회하여야 한다.