Problem overview
This lesson builds a tiny version of the Unix wc command, the part that counts lines. The function countLines(_ lines: [String]) -> Int receives an array of strings and returns how many entries it holds. Every entry is one line, including an empty string "", and an empty array has 0 lines.
The real wc -l counts newline characters in a file. This lesson skips that detail: the input is already split into lines, so counting lines means counting array entries.
For ["hello", "world", "foo", "bar", "baz"] the answer is 5.
Approach
The array already knows its own size. Swift keeps it in the count property, so no loop and no counter variable are needed. Reading count is a constant-time operation: the array doesn't walk its elements to answer.
Step by step
- Return
lines.count. It is anInt, which is exactly the return type in the signature.
The solution in Swift
func countLines(_ lines: [String]) -> Int {
return lines.count
}
The function sits inside the lesson's Solution class, so it is a method. The parameter is declared as _ lines, which means callers write countLines(["a", "b"]) without a label.
Why not a loop?
You could write the count by hand:
var total = 0
for _ in lines {
total += 1
}
It gives the same answer, but it visits every element to do what count does in one step. The underscore in for _ in lines says the loop never uses the element itself. When a built-in property answers the question, use it: the code is shorter and there is no counter to initialise or forget to update.
The related property isEmpty answers a narrower question. lines.isEmpty is true exactly when lines.count == 0, and it reads better when you only need to know whether any lines exist.
Count tracks the array
The property always reflects the current contents, so it changes as the array does:
var lines = ["hello", "world"]
print(lines.count) // 2
lines.append("")
print(lines.count) // 3
print(lines[0].count, lines[2].count) // 5 0
The output is 2, 3 and then 5 0. The appended blank line adds one to the array's count even though that line has zero characters.
Edge cases and common mistakes
- Blank lines count.
["", ""]has two entries, so the result is 2. The function counts entries, not characters. - An empty array gives 0, and
[""], one blank line, gives 1. These two are different inputs with different answers. - A trailing newline is a data question, not a code one. Splitting the text
"a\nb\n"on newlines while keeping empty pieces gives three entries,"a","b"and"", and this function would report 3. Whether that last empty piece is a line is decided before the array reachescountLines. - Don't count characters. A
Stringalso has acount, but it counts characters. Herecountis called on the array, so it counts strings.
Complexity
Time is O(1): an array stores its element count, so reading it doesn't depend on how many lines there are. Extra space is O(1) too, because the function creates nothing and passing the array in doesn't copy it unless the function changes it. A hand-written loop would take O(n) time for the same result.
Testing
Try these inputs in the editor above:
| Input | Result |
|---|---|
["hello", "world", "foo", "bar", "baz"] | 5 |
["", ""] | 2 |
[""] | 1 |
[] | 0 |
