Start learning free

LESSON 229 OF 292 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Frequency in Swift: Split and Count

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return a Dictionary where each word of the sentence is a key, and its value is the number of times that word appears.

The words are in lower case and separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.

Example 1:

Input: sentence = "the cat and the hat"
Output: {"the": 2, "cat": 1, "and": 1, "hat": 1}
Explanation: "the" appears twice. Every other word appears once.

Example 2:

Input: sentence = "go go go"
Output: {"go": 3}
Explanation: The same word three times gives one key, "go", with the value 3.

Example 3:

Input: sentence = "hello"
Output: {"hello": 1}
Explanation: A sentence of one word: that word appears once.
STEP 1 OF 7
    Ctrl + Enter to check

    SWIFT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in Swift, explained

    Problem overview

    The function wordFrequency receives a sentence, a string of lowercase words separated by single spaces, and returns a dictionary that maps each word to how many times it appears. The sentence has at least one word, and the order of the entries doesn't matter.

    For "the cat and the hat" the answer has four entries: "the" is 2, and "cat", "and" and "hat" are 1 each.

    Approach: split, then count

    The problem has two parts. First, cut the sentence into words. Then count them with a dictionary, the same way you would count letters: a word that is already a key gets its count increased, and a new word starts at 1.

    Splitting is done with split(separator: " "), which cuts the string at every space and returns the pieces between the spaces.

    Step by step

    1. Split the sentence with sentence.split(separator: " ") and keep the result in a let named words.
    2. Create counts as an empty [String: Int] with var.
    3. Loop over the pieces with for piece in words.
    4. Convert the piece to a String with String(piece).
    5. Bind the current count with if let count = counts[word] and store count + 1.
    6. Start new words at 1 in the else branch.
    7. Return counts after the loop.

    On "the cat and the hat" the split gives the pieces "the", "cat", "and", "the", "hat". The first "the" creates its entry with 1, "cat" and "and" do the same, the second "the" finds the entry and raises it to 2, and "hat" is new. The loop ends with the four entries listed above.

    The pattern is the same one used to count letters. Only the thing being counted changed: pieces of a split instead of characters of a string.

    The solution in Swift

    class Solution {
        func wordFrequency(_ sentence: String) -> [String: Int] {
            let words = sentence.split(separator: " ")
            var counts = [String: Int]()
            for piece in words {
                let word = String(piece)
                if let count = counts[word] {
                    counts[word] = count + 1
                } else {
                    counts[word] = 1
                }
            }
            return counts
        }
    }
    

    Swift details

    • split returns substrings. The type of sentence.split(separator: " ") is [Substring]. A Substring is a view into the original string, not a String, and the dictionary's keys are String. That is why each piece goes through String(piece) before it is used as a key.
    • The separator is a character. " " in split(separator: " ") is read as a single Character, so it matches each space.
    • Optional lookup. counts[word] is an Int?, nil for a word that hasn't been seen. if let runs its body only when a count exists, and the else branch handles the first sighting.
    • Dictionaries are unordered. The entries can print in any order, and the order can differ between runs.

    Edge cases and common mistakes

    • Repeated word. "go go go" gives a single key, "go", with the value 3.
    • One word. "hello" gives one entry, "hello": 1.
    • Extra spaces. The lesson promises single spaces. With two spaces in a row, split(separator: " ") still drops the empty piece between them: "a b".split(separator: " ") gives ["a", "b"]. Passing omittingEmptySubsequences: false would keep it, giving ["a", "", "b"], and the empty string would then be counted as a word.
    • Forgetting to convert. Using the Substring directly as a key of a [String: Int] dictionary doesn't compile: the compiler reports that it cannot convert a value of type Substring to the expected argument type String.
    • Counting the pieces in a loop but reading counts[word] as a plain number. It is an optional until you unwrap it.

    Testing

    Entries are listed in alphabetical order here for readability.

    • "the cat and the hat" gives and: 1, cat: 1, hat: 1, the: 2.
    • "go go go" gives go: 3.
    • "hello" gives hello: 1.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free