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
- Store the number of lines in a
letnamednumLines, using the array'scount. It never changes, soletis the right choice. - Create
numWordsas avarstarting at 0. - Create
numCharsthe same way. Both are totals that the loop will grow. - Loop over the lines with
for line in lines. The closing brace goes in right away, and the next three steps sit inside it. - Trim the line into a
letnamedtrimmedwithtrimmingCharacters(in: .whitespaces), which removes spaces and tabs from both ends. - Add the words when
trimmedis not empty, by splitting it on whitespace and counting the pieces. A line with nothing but spaces is skipped. - Add the characters by adding
line.counttonumChars. This uses the originalline, nottrimmed, because spaces count as characters. - Return the line count for
"l"withString(numLines), which turns the integer into text. The function returns a string, never a number. - Return the word count for
"w"the same way. - Return the character count for
"c"the same way. - Return all three as one string for every other mode, with
\tbetween 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:
trimmingCharacterscomes from Foundation. It isn't part of the standard library. In a file that doesn't import Foundation,line.trimmingCharacters(in: .whitespaces)fails withvalue of type 'String' has no member 'trimmingCharacters'..whitespacesis 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 asif 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 anIntto 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 anIntmust be wrapped inString(...)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:
| Mode | Result |
|---|---|
"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".
