[Swift] Collection Types - 3. Dictionaries

Byunghoon Lee·2021년 7월 12일
1

iOS

목록 보기
4/11
post-thumbnail

사전 (Dictionaries)

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

빈 Dictionary 생성

var nameOfIntegers: [Int: String] = [:]
		   or
var namesOfIntegers = [Int: String]()

namesOfIntegers[16] = "sixteen"
print(namesOfIntegers) // [16: "sixteen"]

// 초기화 

namesOfIntegers = [:]

리터럴을 이용한 Dictionary 생성

[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"]

Dictionary의 접근 및 변경

갯수 확인

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"]

변경되기 전 값(value) 가져오기

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"]

삭제되기 전 값(value) 가져오기

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."

Dictiionary 반복 (for-in Loops)


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 공식문서

profile
Never never never give up!

0개의 댓글