https://developer.apple.com/documentation/swift/dictionary/init(grouping:by:)
init(grouping:by:) | Apple Developer Documentation
Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.
developer.apple.com
낯선 방식의 생성자이어서 기록해본다.
let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })
// ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]
매개변수 이름을 보면 유추할 수 있듯이 grouping할 리스트를 grouping 매개변수에 담고
어떤 것을 기준으로 grouping 할 것인지 매개변수 by에 전달한다.
아래와 같은 방식도 가능하다.
let students = [
("Alice", "Math", 90),
("Bob", "Math", 85),
("Charlie", "Science", 95),
("Alice", "Science", 100),
("Bob", "History", 70)
]
let groupedBySubject = Dictionary(grouping: students) { $0.1 }
/*
[
"Math": [("Alice", "Math", 90), ("Bob", "Math", 85)],
"Science": [("Charlie", "Science", 95), ("Alice", "Science", 100)],
"History": [("Bob", "History", 70)]
]
*/
'iOS > Swift' 카테고리의 다른 글
[Swift/Xcode] 하나의 빌드 설정에 여러 xconfig을 등록하는 방법 (0) | 2024.07.27 |
---|---|
[Swift] 이미지 크기 Resize 방법 세 가지 (0) | 2024.07.20 |
[Swift] Coordinator 패턴으로 화면 전환 +DIContainer(Swinject) (0) | 2024.07.13 |
[Swift] KeyPath 이해하기 (0) | 2024.07.11 |