Dictionary(grouping: by:) - Order of sequence returned

I was trying to group an array. For convenience I have used an example from the documentation.

Question:

  1. Is the sequence returned for each letter ordered guaranteed to be in the same order as the input ?

Note:

  • Based on my testing it seems to be ordered, just wanted to check if it was guaranteed to be ordered as the input.
  • Notice the order of Kofi and Kweku are interchanged in example 2.
  • Using Swift 4.2, Xcode: Version 10.1 (10B61)

Example 1:

let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]

let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })

print(studentsByLetter)

["K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"], "E": ["Efua"]]

Example 2:

let students = ["Kweku", "Abena", "Efua", "Kofi", "Akosua"]

let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })

print(studentsByLetter)

["K": ["Kweku", "Kofi"], "A": ["Abena", "Akosua"], "E": ["Efua"]]

Yes. The documentation says:

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.

In general, you may consult the documentation for what is guaranteed by any function if you are unsure if a behavior is actually something you can rely on rather than an implementation detail.

3 Likes

Thank you so much @xwu, I should have read the documentation more carefully.

Really happy it guarantees the same order as the source.

Terms of Service

Privacy Policy

Cookie Policy