Swift
[Swift] Collection - Array, Dictionary, Set
learner._.Kio
2021. 3. 9. 13:56
목차
- Array
- Dictionary
- Set
Dictionary
Dictionary는 사전과 유사한 형태로 데이터를 저장한다.
-
저장된 요소는 정렬되지 않는다.(Unordered Collection) - 정렬의 의미가 없음.
-
Dict에 저장되는 자료형은 모두 같아야 한다. key와 value이 쌍으로 저장되는데 key와 value의 자료형이 모두 같아야 한다.
Dictionary
[key: value, key: value, key: value, ...]
var dict = ["A" : "Apple", "B" : "Banana"]
dict = [:] // 빈 배열
Dictionary Type
Dicitonary<K, V>
[key: value]
let dict1: Dictionary<String, Int>
let dict2: [String:Int]
let words = ["A" : "Apple", "B" : "Banana", "C" : "City"]
let emptyDict: [String: String] = [:]
let emptyDict2 = [String: String]()
let emptyDict3 = Dictionary<String, String>()
words.count // 3
words.isEmpty // false
words["A"] // Apple
words["Apple"] // nil, Apple를 Key로 인식한다. 항상 Key를 통해서 값에 접근한다.
let a = words["E"] // nil, a = optional String
let b = words["E", default: "Empty"] // 연관된 값이 없는 경우 기본값은 리턴, b = non-optional String
for key in words.keys.sorted() {
print(key)
}
for value in words.values {
print(value)
}
// 오름차순 정렬
for key in words.keys.sorted() {
print(key)
}
// 오름차순 정렬
for value in words.values.sorted() {
print(value)
}
let keys = Array(words.keys)
let values = Array(words.values)
Adding Keys and Values (Dict 새로운 요소 추가)
var words = [String: String]()
words["A"] = "Apple"
words["B"] = "Banana"
words.count // 2
words // ["B": "Banana", "A": "Apple"]
words["B"] = "Ball"
words.count // 2
words // ["A": "Apple", "B": "Ball"]
Insert + Update = Upsert
// 저장되어 있던 값을 리턴해주고, 값을 넣어줌
words.updateValue("City", forKey: "C") // nil 리턴하고 ["C":"City"] 추가
words // ["A": "Apple", "B": "Ball", "C": "City"]
words.updateValue("Circle", forKey: "C") // "City" 리턴하고 ["C":"Circle"]로 수정
words // ["C": "Circle", "A": "Apple", "B": "Ball"]
Removing Keys and Values (Dict 개별 요소 삭제)
var words : [String: String] = ["A": "Apple", "B": "Ball", "C": "City"]
words["B"] = nil // 'B' key와 연관된 요소 삭제
words // ["C": "City", "A": "Apple"]
words["Z"] = nil // 존재하지 않는 'Z' key 삭제 -> 아무런 동작X
words.removeValue(forKey: "A") // key에 해당하는 값을 삭제한 후, 그 값을 리턴
words.removeValue(forKey: "A") // nil, 삭제할 값이 없기 때문
words.removeAll() // 전체 요소를 삭제할 때
Comparing Dictionaries (Dict 비교)
-
dict 서로 다른 요소로 정렬되어 있지만, collection이므로 순서는 상관없다.
-
저장되어 있는 key와 value가 동일하다면 같은 dictionary로 판단한다.
let a = ["A": "Apple", "B": "Banana", "C": "City"]
let b = ["A": "Apple", "C": "City", "B": "Banana"]
a == b // true
a != b // false
- 문자열에서는 대소문자를 비교하기 때문에 다른 dict으로 판단한다.
let a = ["A": "Apple", "B": "Banana", "C": "City"]
let b = ["A": "Apple", "C": "City", "B": "banana"] // banana를 소문자로 바꾸면?
a == b // false
a != b // true
- elementsEqual 이해못함
a.elementsEqual(b) { (Ihs, rhs) -> Bool in
return Ihs.key.caseInsensitiveCompare(rhs.key) == .orderedSame
&& Ihs.value.caseInsensitiveCompare(rhs.value) == . orderedSame
}
Finding Elements (Dict 요소 검색)
- Dict은 collection 이기 때문에 값이 매번 달라질 수 있다.
var words = ["A": "Apple", "B": "Banana", "C": "City"]
let c: ((String, String)) -> Bool = {
$0.0 == "B" || $0.1.contains("i")
}
words.contains(where: c) // true
let r = words.first(where: c) // (key "C", value "City") or (key "B", value "Banana")
r?.key // C or B
r?.value // City or Banana
// Dict은 collection 이기 때문에 값이 매번 달라질 수 있다.
words.filter(c)
// ["C": "City", "B": "Banana"], 조건을 만족시키는 배열