티스토리 뷰

Swift 3.0.1 가이드에 대응하는 정리글을 작성하였습니다!!!

Array 정리 최신버전 링크 > http://wlaxhrl.tistory.com/37



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


들어가며

Dictionary는 같은 타입의 Key들과 같은 타입의 Value들이 서로 1:1로 연결되어 있는 콜렉션 타입이다. Key는 그 각각이 Value를 위한 identifier역할을 하고, 저장 순서는 없다. 실제 세계에서의 사전처럼 사용할 콜렉션이 필요할 때 Dictionary를 사용하면 유용하다.


Dictionary Type Shorthand Syntax

Dictionary<Key, Value> 는 [Key: Value] 로 축약해서 쓸 수 있다. Key는 Key로 쓰일 타입, Value는 저장될 값의 타입. 참고로 Key가 될 타입은 Hashable 해야한다(Set 에 저장될 값의 타입과 마찬가지).


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. dictionary 안의 item 개수
print("The airports dictionary contains \(airports.count) items.")
// prints "The airports dictionary contains 2 items.”

// 2. dictionary가 비어있는지 체크
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. item 삽입 및 갱신을 위해 subscript syntax 사용
“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() 메서드 사용
// 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. 특정 key에 해당하는 값 접근 (없다면 nil 반환)
if let airportName = airports["DUB"]
{
    print("The name of the airport is \(airportName).")
}
else
{
    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 지우기 위해 removeValueForKey() 메서드 사용
// dictionary[key] = nil과 같은 동작을 하지만 리턴값이 존재한다
// key에 해당하는 value가 이미 있었다면 그 value를 리턴, 없었다면 nil을 리턴 (리턴 타입이 optional)
if let removedValue = airports.removeValueForKey("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의 뒤에 sort() 메서드를 붙여 for-in loop 를 돌 수 있다.
// 이때의 순서는 < 연산으로 결정된다. 


<참고>


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

Functions  (0) 2016.03.12
Control Flow  (0) 2016.03.03
Collection Types - Set  (0) 2016.03.01
Collection Types - Array  (0) 2016.02.28
Strings and Characters  (0) 2016.02.28
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 31
글 보관함