일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- instance
- Protocol
- initializer
- Unicode
- initalizer
- 디자인패턴
- UIKit
- type
- url
- struct
- delegate
- Xcode
- Swift
- Git
- interpace
- enum
- 스위프트
- IOS
- tuist
- Method
- 이니셜라이저
- init
- extension
- property
- Foundation
- optional
- 코딩테스트
- Terminal
- Class
- String
Archives
- Today
- Total
아리의 iOS 탐구생활
[Swift] Dictionary 본문
반응형
✔️ 특징
키와 값이 쌍으로 이루어진 자료형 [key : value]
순서가 없는 컬렉션이다. > key나 value를 원하는 규칙으로 정렬하면서 순회.
value는 중복 가능, key는 중복 불가
✔️ 기본적인 초기화
let dic: [String : Double] = [:]
let dic2 = [String : Double]()
let dic3 = [1 : "100만원",
2 : "50만원" ,
3 : "10만원"] // 타입유추
✔️ uniqueKeysWithValues
배열에 value를 임의로 추가하여 새 Dictionary로 초기화.
Array > [key, value]
let arr = ["own", "two", "three", "four"]
let dic = Dictionary(uniqueKeysWithValues: zip(arr, 1...4))
// ["own": 1, "two": 2, "three": 3, "four": 4]
✔️ uniquingKeysWith
Dictionary 초기화시 key 기준으로 중복된 값을 체크하여 병합해준다.
[tuple] > dictionary
[(value, value)] > [key : value]
let arr = [("four", 4), ("three", 3), ("own", 1), ("two", 2), ("own", 10)]
var dic = Dictionary(arr, uniquingKeysWith: +)
// [“four": 4, "three": 3, "own": 11, "two": 2]
dic.merge([("two", 20)], uniquingKeysWith: +)
// ["four": 4, "three": 3, "own": 11, "two": 22]
응용하기 (문자열 중복체크하여 카운트)
let str = Dictionary("leeariii".uppercased().map{($0, 1)},uniquingKeysWith:+)
// ["L": 1, "E": 2, "A": 1, "R": 1, "I": 3]
✔️ count(갯수), isEmpty(비었니?)
var container = ["row": 10, "column": 20]
print(container.count) // 2
print(container.isEmpty) // false
✔️ 조회, 추가, 순회, 제거
var container = ["row": 10, "column": 20]
print(container["row"]) // Optional(10)
print(container["column"]) // Optional(20)
container["color"] = 157189 // key와 value 추가
print(container.keys) // ["column", "color", "row"]
print(container.values) // [20, 157189, 10]
for (key, value) in container {
print(key, value)
}
/*
column 20
row 10
color 157189
*/
container.removeValue(forKey: "color") // key를 찾아서 값 제거
✔️ Apple 공식문서 참고
Apple Developer Documentation
developer.apple.com
Apple Developer Documentation
developer.apple.com
Apple Developer Documentation
developer.apple.com
Collection Types — The Swift Programming Language (Swift 5.5)
Collection Types Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordere
docs.swift.org
반응형
'Swift > 자료구조' 카테고리의 다른 글
[Swift] String Options에 대해서 알아보자. (0) | 2021.08.24 |
---|---|
[Swift] Set이란? 값 변경, 집합연산, 포함관계 (0) | 2021.08.11 |
[Swift] for each 와 for in의 차이점 (0) | 2021.08.03 |
[Swift ] 소수점 다루기(ceil, floor, round, String format...) (0) | 2021.08.02 |
[Swift] 배열(Array) 다루기 (0) | 2021.07.30 |
Comments