Dictionary
- Key : Value 가 함께 저장되는 자료구조로 정렬되지 않은 컬렉션
- 값 중복 O / 키 중복 X
- 모든 Key의 자료형은 같아야 하고, Value의 자료형도 같아야 함
Dictionary 생성
// 타입 Annotation으로 생성
var dict1 = [String: Int] = [:]
// 생성자로 생성
var dict2 = [String:Int]()
// 여러 타입 저장
var dict3 = [String: Any] = [:]
// error 발생 !
// -> Key 값은 Hashable이란 프로토콜을 준수하는 자료형만 올 수 있음
var dict4 = [Any: Any] = [:]
Dictionary 갯수 확인
print(dict1.count) // 개수 확인
print(dict1.isEmpty) // 비었는지 확인
Dictionary 요소 접근
var dict = ["height": 165, "age": 24]
print(dict["height"]) // Optional(165)
print(dict["weight"]) // nil
print(dict["height", default: 150]) // 165
print(dict["weight", default: 200]) //200
Dictionary 요소 추가
var dict = ["height": 165, "age": 24]
dict["weight"] = 100 // 해당 키가 없다면 추가 (insert)
dict["height"] = 200 // 해당 키가 있다면 Value 덮어쓰기 (update)
Dictionary 요소 삭제
var dict = ["height": 165, "age": 24]
// Subscript로 삭제 (nil 대입)
dict["height"] = nil
dict["weight"] = nil // 해당 키 없어도 에러 안남
// removeValue(forKey:)
dict.removeValue(forKey: "age") // 삭제 후 삭제된 Value 반환
dict.removeValue(forKey: "weight") // 해당 키 없다면 nil 반환
// removeAll() : 전체 삭제
dict.removeAll()
Key, Value 나열
var dict = ["height": 165, "age": 24]
// key 나열
dict.keys // "height", "age"
dict.keys.sorted() // "age", "height"
// value 나열
dict.values // 165, 24
dict.values.sorted() // 24, 165
Dictionary 비교
var dict1 = ["height": 165, "age": 24]
var dict2 = ["height": 165, "age": 24]
var dict3 = ["height": 165, "weight": 50]
dict1 == dict2 // true
dict1 == dict3 // false
Dictionary 요소 검색
var dict = ["height": 165, "age": 24]
let search: ((String, Int)) -> Bool = {
$0.0.contains("h")
}
// contains(where:) : 해당 클로저 만족하는 요소 하나라도 있을 경우 true
dict.contains(where: search)
// first(where:) : 해당 클로저 만족하는 첫 번째 요소 튜플로 리턴
dict.first(where: search)
// filter : 해당 클로저 만족하는 요소만 모아 새 딕셔너리로 리턴
dict.filter(search)
이 때, 중요한 점 !
딕셔너리 요소 검색 시 클로저를 이용해 검색하는데
클로저의 파라미터 타입은 내가 지정한 딕셔너리의 타입을 갖는 튜플이어야 하고, 반환 타입은 무조건 Bool 이어야 합니다 . . !
Dictionary Value 기준으로 정렬 후 Key 반환
var dict = [Int: Int] = [1: 3, 2: 2, 3: 1]
print(dict.sorted { $0.1 > $1.1 }.map { $0.0 }) // [3, 2, 1]
참고
'iOS > Swift' 카테고리의 다른 글
[Swift] stride 함수 / Set (0) | 2022.10.25 |
---|---|
[Swift] Swift 알고리즘 - 수학 (0) | 2022.10.13 |
[Swift] Swift 알고리즘 - 문자열 / 배열 (0) | 2022.10.11 |
[Swift] 클로저 (Closure) (0) | 2022.09.24 |
[Swift] Class vs. Struct vs. Enum (0) | 2022.09.06 |