Start learning free

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

Word Lengths in Swift: Mapping Words to Their Lengths

Practice Read the full explanation

Given an array of strings words, return an array of integers with the length of every word, in the same order as the words.

The length of a word is the number of letters it has.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: [1, 4, 8]
Explanation: "I" has 1 letter, "love" has 4 and "pancakes" has 8.

Example 2:

Input: words = ["banana", "kiwi", "fig"]
Output: [6, 4, 3]
Explanation: The lengths keep the order of the words: first "banana", then "kiwi", then "fig".

Example 3:

Input: words = ["code"]
Output: [4]
Explanation: One word gives one length.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • The result has one length per word, in the same order as words.
STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Lengths in Swift, explained

    Problem overview

    The function wordLengths takes an array of strings, words, and returns an array of integers: the length of each word, in the same order as the words. The result always has exactly one number per word.

    For ["I", "love", "pancakes"] the answer is [1, 4, 8], because "I" has 1 letter, "love" has 4 and "pancakes" has 8.

    Approach: one output for each input

    Unlike filtering, nothing is skipped here. Each word produces one length, so the loop appends on every pass and the result ends up exactly as long as the input. Because the loop goes through the words in order and always appends at the end, position i of the result belongs to position i of words.

    The length of a word is word.count. In Swift a String is a collection of characters, and count says how many it holds.

    Step by step

    1. Start with an empty array of Int named lengths, declared with var because it grows.
    2. Loop over the words with for word in words.
    3. Append word.count to lengths.
    4. Return lengths after the loop. A return inside the loop would hand back after the first word, with only one length in it.

    Here is the loop on ["I", "love", "pancakes"]. lengths starts as []. After "I" it is [1], after "love" it is [1, 4], and after "pancakes" it is [1, 4, 8]. That final array is what the function returns.

    The result has the same number of items as words, so the two arrays line up index by index: lengths[2] is the length of words[2]. That is useful when a later step needs both a word and its length.

    The solution in Swift

    class Solution {
        func wordLengths(_ words: [String]) -> [Int] {
            var lengths = [Int]()
            for word in words {
                lengths.append(word.count)
            }
            return lengths
        }
    }
    

    Details worth knowing:

    • [Int]() is an empty array whose elements are Int. Swift needs to know the element type, and this spelling gives it.
    • for word in words gives each element in turn as a constant. You can't change word inside the loop, and you don't need to.
    • Uppercase and lowercase letters count the same. "I" and "i" both have length 1, so the constraint about letter case changes nothing.
    • The shorter way. Swift's map turns an array into another array of the same length: words.map { $0.count } gives the same result. The lesson uses the explicit loop so the pattern of building a result is visible.

    It is worth knowing what count measures. It counts characters as a reader sees them: the word "café" written with a combining accent (the letters c, a, f, e followed by an accent mark) still has a count of 4, although it takes 5 Unicode scalars and 6 bytes in UTF-8. The lesson's words use plain English letters, so you won't meet the difference here.

    Edge cases and common mistakes

    • One word. ["code"] gives [4].
    • Order. ["banana", "kiwi", "fig"] gives [6, 4, 3], not a sorted list. The lengths are never rearranged.
    • Using let for lengths. A constant array can't be appended to, and the compiler rejects the append call.
    • Returning too early. The return sits after the closing brace of the loop.

    Testing

    • ["I", "love", "pancakes"] gives [1, 4, 8].
    • ["banana", "kiwi", "fig"] gives [6, 4, 3].
    • ["code"] gives [4].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free