How to group words by first letter in Swift

1 Answer

0 votes
import Foundation

/// Groups words by their first letter.
///
/// - Parameter words: The list of words to group.
/// - Returns: A dictionary where each key is a first letter
///            and each value is an array of words.
func groupByFirstLetter(_ words: [String]) -> [Character: [String]] {

    // Dictionary(grouping:by:) automatically creates:
    //   key   = result of the closure (first letter)
    //   value = array of all items matching that key
    return Dictionary(grouping: words) { word in
        word.first!   // safe because all words are non-empty
    }
}

let words = [
    "Python", "JavaScript", "C", "Java", "C#", "PHP",
    "C++", "Pascal", "SQL", "Rust"
]

let grouped = groupByFirstLetter(words)

// Print each group 
for (letter, group) in grouped {
    print("\(letter): \(group)")
}

// Print the entire dictionary
print(grouped)



/*
run:

J: ["JavaScript", "Java"]
S: ["SQL"]
P: ["Python", "PHP", "Pascal"]
C: ["C", "C#", "C++"]
R: ["Rust"]
["J": ["JavaScript", "Java"], "S": ["SQL"], "P": ["Python", "PHP", "Pascal"], "C": ["C", "C#", "C++"], "R": ["Rust"]]

*/

 



answered Jan 17 by avibootz
...