Start learning free

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

Long Words Only in Swift: Filtering an Array with a Loop

Practice Read the full explanation

Given an array of strings words and an integer n, return the words that are longer than n characters.

A word must be strictly longer than n: a word with exactly n characters is left out. Keep the words in the order they have in words. If no word is long enough, the result is empty.

 

Example 1:

Input: words = ["apple", "kiwi", "banana", "fig"], n = 4
Output: ["apple", "banana"]
Explanation: apple has 5 characters and banana has 6. kiwi has exactly 4, so it is left out, and fig has only 3.

Example 2:

Input: words = ["hi", "to", "be"], n = 3
Output: []
Explanation: No word has more than 3 characters.

Example 3:

Input: words = ["go", "went", "gone", "went"], n = 3
Output: ["went", "gone", "went"]
Explanation: Every word longer than 3 characters is kept, a repeated one too, in its original order.

 

Constraints:

  • words has at least one word, and every word is made of lowercase English letters.
  • n is 0 or more.
STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Long Words Only in Swift, explained

    Problem overview

    The function longWords receives an array of strings, words, and an integer n. It returns a new array with the words that have more than n characters, in the order they had in words. If no word qualifies, the result is an empty array.

    For words = ["apple", "kiwi", "banana", "fig"] and n = 4, the lengths are 5, 4, 6 and 3. Only "apple" and "banana" are longer than 4, so the result is ["apple", "banana"]. "kiwi" has exactly 4 characters, which is not more than 4, so it is left out.

    Approach: collect what passes the test

    This is the basic filtering pattern: start with an empty array, look at each item once, and append the ones that meet a condition. Because the loop visits the words from first to last and each match goes to the end of result, the original order is kept without any extra work.

    The condition is a strict comparison. A word of exactly n characters fails word.count > n, which is what the problem asks for. Writing >= would keep it by mistake.

    Step by step

    1. Create result as an empty [String] declared with var. It has to be a variable because it grows inside the loop.
    2. Loop over words with for word in words, so every word gets a turn.
    3. Test the length with word.count > n.
    4. Append the word inside the if, so only the long ones are added.
    5. Return result after the loop. If nothing matched, it is still empty, which is the right answer.

    Tracing the first example with n = 4: "apple" has 5 characters, 5 > 4, so it is appended. "kiwi" has 4, and 4 > 4 is false, so it is skipped. "banana" (6) is appended and "fig" (3) is skipped. The loop ends with result holding "apple" and "banana", in that order, and the function returns it.

    The same loop works for any condition. Change the test to word.count < n, or to a test on the first letter, and you get a different filter with the same shape.

    The solution in Swift

    class Solution {
        func longWords(_ words: [String], _ n: Int) -> [String] {
            var result = [String]()
            for word in words {
                if word.count > n {
                    result.append(word)
                }
            }
            return result
        }
    }
    

    A few Swift details:

    • [String]() creates an empty array of strings. Writing var result: [String] = [] means the same thing.
    • count counts characters. A String in Swift is a collection of Character values, and word.count is how many of them it holds. A character is what a reader sees as one symbol, so "café".count is 4 even when the accent is stored as a separate combining mark. The lesson's words are plain lowercase letters, so the number is simply the letter count.
    • Value types. Arrays are values in Swift. words is never changed; the function builds and returns a separate array.

    Edge cases and common mistakes

    • Using >=. With n = 4, "kiwi" would be wrongly included.
    • Nothing long enough. ["hi", "to", "be"] with n = 3 returns [].
    • Repeated words. ["go", "went", "gone", "went"] with n = 3 returns ["went", "gone", "went"]: duplicates are kept, each in its own position.
    • n = 0. Every word has at least one letter, so every word is returned: ["ab"] with n = 0 gives ["ab"].
    • Returning inside the loop. A return in the if would stop at the first long word. The return belongs after the loop.

    Testing

    • ["apple", "kiwi", "banana", "fig"], n = 4 gives ["apple", "banana"].
    • ["hi", "to", "be"], n = 3 gives [].
    • ["go", "went", "gone", "went"], n = 3 gives ["went", "gone", "went"].
    • ["ab"], n = 0 gives ["ab"].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free