티스토리 뷰

Apple 제공 Swift 프로그래밍 가이드(3.0.1)의 Collection Types 중 Dictionary 부분을 공부하며 정리한 글입니다. 개인적인 생각도 조금 들어가있습니다.


들어가며

Dictionary는 같은 타입의 Key들과 같은 타입의 Value들이 서로 1:1로 연결되어 있는 Collection 타입이다. Key는 그 각각이 유니크하며 Value를 위한 identifier역할을 한다. 저장 순서는 따지지 않는다. 실제 세계에서의 사전처럼 사용할 Collection Type이 필요할 때 Dictionary를 사용할 수 있다.

<note> Swift’s Dictionary type is bridged to Foundation’s NSDictionary class.


Dictionary Type Shorthand Syntax

Dictionary<Key, Value> 는 [Key: Value] 로 축약해서 쓸 수 있다. 이때 Key는 Key로 쓰일 타입, Value는 저장될 값의 타입.

Key가 될 타입은 Hashable 해야한다. 참고로 Set 에 저장될 값의 타입도 그러했다. 유니크한 값인지를 따질 수 있는 Type이어야 한다는 공통점이 있다.


Creating an Empty Dictionary

 // 1. empty dictionary 생성
var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

// 2. dictionary Literal로 dictionary 생성
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
// var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] 라고만 써도 타입을 유추해준다



Accessing and Modifying a Dictionary

 // 1. item 개수를 체크하기 위해 -> count 프로퍼티
print("The airports dictionary contains \(airports.count) items.")
// prints "The airports dictionary contains 2 items.”

// 2. 비어있는지 체크하기 위해 -> isEmpty 프로퍼티
if airports.isEmpty {
    print("The airports dictionary is empty.")
}
else {
    print("The airports dictionary is not empty.")
}
// prints "The airports dictionary is not empty.”


// 3. subscript syntax를 사용해서 item 삽입 및 갱신
airports["LHR"] = "London"
// the airports dictionary now contains 3 items

airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow”


// 4. item 삽입 및 갱신을 위해 -> updateValue(_:forKey:) 메서드
// dictionary[key] = "value" 와 같은 동작을 하지만 리턴값이 존재한다
// key에 해당하는 value가 이미 있었다면 그 value를 리턴하고
// 없었다면 nil을 리턴 (리턴 타입이 optional)
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    // 새로운 값으로 대체되었음을 알 수 있다
    print("The old value for DUB was \(oldValue).")
}
// prints "The old value for DUB was Dublin.”


// 5. subscript syntax를 사용해서 특정 key에 해당하는 값 접근
if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
}
else {
    // key에 해당하는 값이 없었다면 nil를 반환한다
    print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport.”


// 6. 특정 item 지우기 (key-value pair 지우기)
airports["APL"] = "Apple International"
// "Apple International" is not the real airport for APL, so delete it
airports["APL"] = nil
// APL has now been removed from the dictionary

// 7. 특정 item 지우기 위해 -> removeValue(forKey:) 메서드
// dictionary[key] = nil과 같은 동작을 하지만 리턴값이 존재한다
// key에 해당하는 value가 이미 있었다면 그 value를 리턴하고
// 없었다면 nil을 리턴 (리턴 타입이 optional)
if let removedValue = airports.removeValue(forKey: "DUB") {
    print("The removed airport's name is \(removedValue).")
}
else {
    print("The airports dictionary does not contain a value for DUB.")
}
// prints "The removed airport's name is Dublin Airport.”



Iterating Over a Dictionary

for-in loop 에서 Dictionary를 순회할 수 있다. 각 Item은 (key, value) 튜플을 반환한다.

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


// key만으로, 혹은 value만으로 for-in loop 를 돌 수 있다.
for airportCode in airports.keys
{
    print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR
 
for airportName in airports.values
{
    print("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow


// <참고> dictionary의 key나 value만을 array로 받을 수 있다
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
 
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]


// <참고> dictionary는 순서가 없기 때문에, 특정한 순서를 원한다면
// 프로퍼티 keys나 values의 뒤에 sorted() 메서드를 붙여 for-in loop
// (소팅은 < 연산으로 한다.)


<참고 - 뒷장에 나오는 부분>

아직 이해를 할 필요는 없습니다. 그냥 맛보기로...

var dict: [String: String] = ["b": "bValue", "a": "aValue"]

// 이 dictionary의 sort는 이런 식으로 할 수 있다
dict.sorted { (first, second) -> Bool in
    print(first, second)
    return first.key < second.key
}
// 여기서의 first, second는 dictionary의 Item(tuple type)이다
// 함수의 맨 마지막 파라미터로 클로저가 들어오면 괄호는 생략가능
// print ("a", "aValue") ("b", "bValue")


// 또한 위를 아래와 같이 축약할 수 있다
dict.sorted { $0.0 < $1.0 }
// $0와 $1는 각각 첫 번째와 두 번째로 들어오는 파라미터
// return은 생략가능


'Swift 공식 가이드 > Swift 3' 카테고리의 다른 글

Functions  (0) 2017.02.19
Control Flow  (0) 2017.02.15
Collection Types - Set  (0) 2017.02.11
Collection Types - Array  (0) 2017.02.11
Strings and Characters  (2) 2017.02.05
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함