Start learning free

LESSON 12 OF 71 · PROJECTS: COMMAND-LINE TOOLS

wc in Swift: A Mode Flag with String Interpolation

Practice Read the full explanation

Combine the previous three versions of wc. Given a list of lines and a mode flag, return the requested count(s) as a string. This is our own simplified interface, not the real wc flags: the real tool combines flags (such as -lw) and pads its columns with spaces.

Function signature:

func wc(_ lines: [String], _ mode: String) -> String

Mode values:

  • "l" → line count, as a string.
  • "w" → word count (whitespace-separated tokens), as a string.
  • "c" → character count (lines only, no separating newlines), as a string.
  • "all" → lines + "\t" + words + "\t" + chars.

The "c" count is the one from v3 (the sum of the line lengths, no newlines). Any other mode value, for example "x" or "L" (modes are case-sensitive), gives the same result as "all". For an empty list, "l", "w" and "c" give "0" and "all" gives "0<TAB>0<TAB>0". The input is plain ASCII text.

Example:

Input: lines = ["hello", "world"], mode = "all"

Output: "2\t2\t10"

2 lines, 2 words (one per line), 10 characters total.


Compute all three counts in a single pass through lines, then branch on mode to pick the return value.

let numLines = lines.count
var numWords = 0
var numChars = 0
for line in lines {
    let trimmed = line.trimmingCharacters(in: .whitespaces)
    if !trimmed.isEmpty { numWords += trimmed.split(whereSeparator: { $0.isWhitespace }).count }
    numChars += line.count
}
Then String(numLines) / String(numWords) / String(numChars) as needed, or assemble all three with tabs.

The full solution:
class Solution {
    func wc(_ lines: [String], _ mode: String) -> String {
        let numLines = lines.count
        var numWords = 0
        var numChars = 0
        for line in lines {
            let trimmed = line.trimmingCharacters(in: .whitespaces)
            if !trimmed.isEmpty { numWords += trimmed.split(whereSeparator: { $0.isWhitespace }).count }
            numChars += line.count
        }
        if mode == "l" { return String(numLines) }
        if mode == "w" { return String(numWords) }
        if mode == "c" { return String(numChars) }
        return "\(numLines)\t\(numWords)\t\(numChars)"
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in Swift, explained

    Problem overview

    The fourth version of the wc project merges the three before it into one function: wc(_ lines: [String], _ mode: String) -> String. It receives the lines and a mode flag and returns the requested count as a string:

    • "l" gives the number of lines.
    • "w" gives the number of words, meaning whitespace-separated tokens.
    • "c" gives the number of characters, the sum of the line lengths with no newlines.
    • "all" gives the three numbers joined by tab characters, in the order lines, words, characters.

    Any other mode, such as "x" or "L", behaves like "all", because modes are case-sensitive. For ["hello", "world"] with mode "all" the result is "2\t2\t10": 2 lines, 2 words and 10 characters. For an empty array, "l", "w" and "c" give "0" and "all" gives "0\t0\t0". The interface is this lesson's own and is simpler than the real tool's combined flags and padded columns.

    Approach

    Computing each count separately would mean three loops, or one loop per requested mode. The simpler design is to compute all three numbers in a single pass and decide at the end which one to return. The work is the same whichever mode is asked for, and the code never has to repeat a loop.

    The line count needs no loop: it is the size of the array. The word and character counts both grow as the loop visits each line, so they start at 0 and accumulate. The word count reuses the idea from version 2, splitting on whitespace and counting the pieces. The character count reuses version 3, adding line.count.

    After the loop, a chain of if statements handles the three single-count modes, each returning early. Whatever reaches the last line, whether "all" or any unknown flag, gets the combined answer, which is how the statement's rule for unknown modes comes out without extra code.

    Step by step

    1. Store the number of lines in a let named numLines, using the array's count. It never changes, so let is the right choice.
    2. Create numWords as a var starting at 0.
    3. Create numChars the same way. Both are totals that the loop will grow.
    4. Loop over the lines with for line in lines. The closing brace goes in right away, and the next three steps sit inside it.
    5. Trim the line into a let named trimmed with trimmingCharacters(in: .whitespaces), which removes spaces and tabs from both ends.
    6. Add the words when trimmed is not empty, by splitting it on whitespace and counting the pieces. A line with nothing but spaces is skipped.
    7. Add the characters by adding line.count to numChars. This uses the original line, not trimmed, because spaces count as characters.
    8. Return the line count for "l" with String(numLines), which turns the integer into text. The function returns a string, never a number.
    9. Return the word count for "w" the same way.
    10. Return the character count for "c" the same way.
    11. Return all three as one string for every other mode, with \t between the numbers. String interpolation, \(name) inside the quotes, puts each number into the text.

    The solution in Swift

        func wc(_ lines: [String], _ mode: String) -> String {
            let numLines = lines.count
            var numWords = 0
            var numChars = 0
            for line in lines {
                let trimmed = line.trimmingCharacters(in: .whitespaces)
                if !trimmed.isEmpty { numWords += trimmed.split(whereSeparator: { $0.isWhitespace }).count }
                numChars += line.count
            }
            if mode == "l" { return String(numLines) }
            if mode == "w" { return String(numWords) }
            if mode == "c" { return String(numChars) }
            return "\(numLines)\t\(numWords)\t\(numChars)"
        }
    

    The details a learner might trip on:

    • trimmingCharacters comes from Foundation. It isn't part of the standard library. In a file that doesn't import Foundation, line.trimmingCharacters(in: .whitespaces) fails with value of type 'String' has no member 'trimmingCharacters'.
    • .whitespaces is spaces and tabs only. It doesn't include newline characters, which is fine here because each line is already separate.
    • The trim is a safeguard, not a necessity. split(whereSeparator:) already drops empty pieces, so a blank line gives 0 words even without it. The lesson's version states the "no words" case explicitly.
    • Braces are required. Swift has no brace-less if, so one-line statements are written as if mode == "l" { ... }.
    • Mode is compared with ==. For strings it compares contents, and it is case-sensitive, so "L" doesn't match "l".
    • Interpolation and String(_:) both convert an Int to text. Interpolation is handier when you build a longer string.

    Complexity

    Time is O(n), where n is the total number of characters, since each line is trimmed, split and counted a constant number of times. Extra space is proportional to the longest line, for the trimmed copy and the array of word pieces, plus a handful of integers.

    Edge cases and common mistakes

    • Unknown modes. "x" and "L" return the full three-number string. Don't add a branch for "all" that the others can't reach.
    • The separators are tabs. The result for "all" is "2\t2\t10" with real tab characters, not spaces and not newlines.
    • Returning a number. The function's type is String, so an Int must be wrapped in String(...) first.
    • Counting characters from the trimmed line. That would drop the spaces at the ends of the lines.
    • Counting blank lines as words. They add 0 words but still count as lines.

    Testing

    For the lines [" two words ", "", "tab\tsep"], the results by mode are:

    ModeResult
    "l""3"
    "w""4"
    "c""19"
    "all""3\t4\t19"
    "L""3\t4\t19"

    Two more cases: ["hello", "world"] with "all" gives "2\t2\t10", and [] with "x" gives "0\t0\t0".

    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free