Start learning free

LESSON 9 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Line Count in Swift: Building wc with Array.count

Practice Read the full explanation

Build a tiny version of the Unix wc command. Given a list of lines, return the total number of lines as an integer.

Function signature:

func countLines(_ lines: [String]) -> Int

Example:

Input: lines = ["hello", "world", "foo", "bar", "baz"]

Output: 5

Every entry of the list is one line, even an empty string "". An empty list has 0 lines.


The number of lines is just the array's element count. Use lines.count — no loop needed.

A one-liner:
class Solution {
    func countLines(_ lines: [String]) -> Int {
        return lines.count
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Wc V1 in Swift, explained

    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

    1. Return lines.count. It is an Int, 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 reaches countLines.
    • Don't count characters. A String also has a count, but it counts characters. Here count is 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:

    InputResult
    ["hello", "world", "foo", "bar", "baz"]5
    ["", ""]2
    [""]1
    []0
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free