[Key: Value]
형태로 Dictionary를 선언해 사용할 수 있습니다.
var nameOfIntegers: [Int: String] = [:]
or
var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"
print(namesOfIntegers) // [16: "sixteen"]
// 초기화
namesOfIntegers = [:]
[key 1: value 1, key 2: value 2, key 3: value 3]
형태로 사전을 선언할 수 있습니다.
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
※ 참고 - key: value의 타입이 서로 같으면 타입 생략이 가능합니다.
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
print("The airports dictionary contains \(airports.count) items.")
// The airports dictionary contains 2 items.
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary isn't empty.")
}
// "The airports dictionary isn't empty."
airports["LHR"] = "London"
print(airports) // ["YYZ": "Toronto Pearson", "LHR": "London", "DUB": "Dublin"]
airports["LHR"] = "London Heathrow"
print(airports) // ["YYZ": "Toronto Pearson", "LHR": "London Heathrow", "DUB": "Dublin"]
updateValue(_:forKey:)
메서드를 사용 합니다.
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
// "The old value for DUB was Dublin."
print(airports) // ["YYZ": "Toronto Pearson", "LHR": "London Heathrow", "DUB": "Dublin Airport"]
// 삭제할것 먼저 추가.
// APL 이라는 key와, Apple International 이라는 value 추가
airports["APL"] = "Apple International"
print(airports) // ["APL": "Apple International", "YYZ": "Toronto Pearson", "DUB": "Dublin Airport", "LHR": "London Heathrow"]
// 삭제
airports["APL"] = nil
print(airports) // ["YYZ": "Toronto Pearson", "DUB": "Dublin Airport", "LHR": "London Heathrow"]
removeValue(forKey:)
메서드를 사용 합니다.
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 airportKeyValue in airports {
print("Airport code: \(airportKeyValue)")
}
//Airport code: (key: "YYZ", value: "Toronto Pearson")
//Airport code: (key: "LHR", value: "London Heathrow")
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
참고 : Swift 공식문서