본문 바로가기
TIL

[240319] 배열과 딕셔너리

by 줍 2024. 3. 19.

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")]]