post list

2015년 2월 15일 일요일

Swift(스위프트) 강좌: 빠르게 시작하기 3

딕셔너리(Dictionaries)


스위프트의 딕셔너리는 특정한 타입의 키와 그에 따른 값을 저장한다.  
Objective-C NSDictionary NSMutableDictionary 클라스와는 다릅니다.
NSDictionary와 NSMutableDictionary 클라스는 어느 종류의 객체든 키와 값으로 저장이 가능한 반면 그 저장된 객체의 속성에 대한 어떠한 정보도 제공하지 않습니다. 

딕셔너리 표현식 (Dictionary Literals)


1
2
3
4
5
6
7
// full form
var airports: Dictionary<String , String
= ["YYZ" : "Toronto Pearson" , "DUB" : "Dublin"]
// short form
var number: [ Int : String] = [1 : "one"2"two" ]
// shorter from
var city = ["seoul" : 02 , "daegu" : 053 ]
cs

딕셔너리의 접근 및 수정 Accessing and Modifying a Dictionary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//개수 확인
println("The airports dictionary contains \(airports.count) items")
// 비었는지 확인
if airports.isEmpty {
    println(" The airports dictinary is empty")
}
// 추가
airports["LHR"] = "London"
// 수정
airports["LHR"] = "London Heathrow"
// 수정 : 메소드를 사용
// return 값은 밸류 타입에 해당하는 Optinal 값
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    println("The old value for DUB was \(oldValue).")
}
// 삭제 
airports["YYZ"] = nil
// 삭제 : 메소드 사용 
// return 값은 삭제된 값
if let removedValue = airports.removeValueForKey("DUB") {
    println("The removed airport's name is \(removedValue)")
}
cs

빈 딕셔너리 만들기 Creating an Empty Dictionary


1
var namesOfInteagers = [Int : String]()
cs


만약 context에서 이미 타입에 대한 정보를 가지고 있다면  [:] 통해서 빈딕셔너리를 초기화할 수 있습니다.. 


1
2
namesOfInteagers[16] = "sixteen"
namesOfInteagers = [:]
cs









댓글 없음:

댓글 쓰기