Initializerswift 6.0.1Swift

    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

    Parameters

    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.

    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".

    Other members in extension

    Typealiases

    • typealias Element

      The element type of a dictionary: a tuple containing an individual key-value pair.

    Type members