Roen의 iOS 개발로그

[Dictionary Initializer] init(grouping:by:)

by Steady On

init(grouping:by:)

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.

키가 지정된 클로저에 의해 반환된 그룹이고 값은 각 키로 반환된 요소의 배열인 새로운 딕셔너리를 생성한다.

 

선언

init<S>(
    grouping values: S,
    by keyForValue: (S.Element) throws -> Key
) rethrows where Value == [S.Element], S : Sequence

매개변수

values

A sequence of values to group into a dictionary.

사전으로 그룹화할 값의 시퀀스

keyForValue

A closure that returns a key for each element in values.
값의 각 요소에 대한 키를 반환하는 클로저

 

논의

The arrays in the “values” position of the new dictionary each contain at least one element, with the elements in the same order as the source sequence.

새로운 딕셔너리의 "values" 위치에 있는 배열은 원래의 시퀀스와 동일한 순서로 각각 적어도 하나의 요소를 포함한다.

The following example declares an array of names, and then creates a dictionary from that array by grouping the names by first letter:

다음 예제는 이름 배열을 선언한다. 그리고 이름의 첫번째 글자로 그룹화된 배열로 딕셔너리를 생성한다.

let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })
// ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]

The new studentsByLetter dictionary has three entries, with students’ names grouped by the keys "E", "K", and "A".

새로운 studentsByLetter 딕셔너리는 "E", "K", "A"를 키로 그룹화된 학생들 이름으로 세개의 항목을 가진다.

 


참고자료

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

 

블로그의 정보

Roen의 iOS 개발로그

Steady On

활동하기