1. 배열에 각 요소가 몇개씩 있는지 세기 위해 딕셔너리를 이용할 수 있다.
var dictX: [String: Int] = [:]
var dictY: [String: Int] = [:]
X.forEach { dictX[String($0), default: 0] += 1 }
Y.forEach { dictY[String($0), default: 0] += 1 }
또, 딕셔너리의 생성자 Dictionary(grouping:by:)를 이용하면 배열의 요소를 어떤 기준(key)에 따라 그룹핑(value)하여 딕셔너리로 나타낼 수 있다!
let a = [1, 2, 3, 3, 5, 5]
Dictionary(grouping: a) { $0 } // [2: [2], 1: [1], 3: [3, 3], 5: [5, 5]]
예를 들어 Movie 데이터를 genre별로 분류해 딕셔너리를 만들고 싶다면 이렇게 할 수 있다.
let a = Movie(title: "Past Lives", genre: "Drama")
let b = Movie(title: "Anatomy of Fall", genre: "Drama")
let c = Movie(title: "Pamyo", genre: "Mystery")
let movies = [a, b, c]
let movieDict = Dictionary(grouping: movies) { $0.genre }
// ["Drama": [__lldb_expr_26.Movie(title: "Past Lives", genre: "Drama"), __lldb_expr_26.Movie(title: "Anatomy of Fall", genre: "Drama")],
// "Mystery": [__lldb_expr_26.Movie(title: "Pamyo", genre: "Mystery")]]
'TIL' 카테고리의 다른 글
[240321] 시뮬레이터 화면 안뜸/동적, 정적타입 (0) | 2024.03.21 |
---|---|
[240320] Segue/Navigation Controller/didSelectRowAt/스와이프 (0) | 2024.03.20 |
[240318] 함수 파라미터 주석/랜덤 숫자 (0) | 2024.03.18 |
[240317] % 활용하기 (0) | 2024.03.17 |
[240316] 재귀함수 (0) | 2024.03.16 |