티스토리 뷰

728x90

사전(Dictionaries)

dictionary는 정의된 순서 없이 collection에 동일한 타입의 키와, 동일한 타입의 값을 연결합니다. 

 

NOTE
Swift의 Dictionary 타입은 Foundation의 NSDictionary 클래스를 bridge한 타입 입니다.

 

선언

일반적인 Dictionary 형태는 아래와 같습니다.

Dictionary<Key, Value>

 

 

축약형 Dictionary

[Key: Value]의 형태로 Dictionary를 선언해 사용할 수 있습니다.

 

빈 Dictionary의 생성

var namesOfIntegers = [Int: String]()
// 또는
var namesOfIntegers: [Int: String] = [:]
var namesOfIntegers = [Int: String]()    // [:]
namesOfIntegers[16] = "sixteen"          // "sixteen"
namesOfIntegers                          // [16: "sixteen"]
namesOfIntegers = [:]                    // [:]

 

 

리터럴을 이용한 Dictionary 생성

 

아래와 같은 형태로 Dictionary를 선언할 수 있습니다.

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

 

Dictionary의 접근과 변경

print("The airports dictionary contains \(airports.count) items.")
// The airports dictionary contains 2 items.

 

빈 Dictionary 확인

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", "DUB": "Dublin", "LHR": "London"]

print("airports items are \(airports.count)")
// airports items are 3

 

값 변경

// 값 변경
airports["LHR"] = "London Heathrow"
print(airports)
// ["YYZ": "Toronto Pearson", "DUB": "Dublin", "LHR": "London Heathrow"]

// 또는

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)
// ["LHR": "London Heathrow", "YYZ": "Toronto Pearson", "DUB": "Dublin Airport"]

 

 

값 삭제

// "APL": "Apple International" 추가
airports["APL"] = "Apple International"
print(airports)
// ["DUB": "Dublin Airport", "LHR": "London Heathrow", "APL": "Apple International", "YYZ": "Toronto Pearson"]

// "APL": "Apple International" 삭제
airports["APL"] = nil
print(airports)
// ["DUB": "Dublin Airport", "LHR": "London Heathrow", "YYZ": "Toronto Pearson"]

// 또는

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.
print(airports)
// ["LHR": "London Heathrow", "YYZ": "Toronto Pearson"]

 

Dictionary 순회

 

for-in loop로 각 아이템에 있는 (key, value)를 return할 수 있습니다.

 

for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// LHR: London Heathrow
// YYZ: Toronto Pearson

 

key 값 접근

for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
// Airport code: LHR
// Airport code: YYZ

 

value 값 접근

for airportName in airports.values {
    print("Airport name: \(airportName)")
}
// Airport name: London Heathrow
// Airport name: Toronto Pearson

 

Dictionary의 key, value 배열화

let airportCodes = [String](airports.keys)
// ["LHR", "YYZ"]

let airportNames = [String](airports.values)
// ["London Heathrow", "Toronto Pearson"]

 

NOTE
Swift의 Dictionary는 순서가 지정 되지 않습니다. 
순서대로 정렬하고 싶다면, sorted() 메소드를 사용하시면 됩니다.
728x90