Start learning free

LESSON 4 OF 71 · PROJECTS: COMMAND-LINE TOOLS

cat with Many Files in Swift: Flattening Nested Arrays

Practice Read the full explanation

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

func concatCat(_ allLines: [[String]]) -> String

Example:

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

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Build a flat [String] with a nested loop, preserving order. Then return flat.joined(separator: "\n").

var flat: [String] = []
for fileLines in allLines {
    for line in fileLines {
        flat.append(line)
    }
}
return flat.joined(separator: "\n")


The full solution:
class Solution {
    func concatCat(_ allLines: [[String]]) -> String {
        var flat: [String] = []
        for fileLines in allLines {
            for line in fileLines {
                flat.append(line)
            }
        }
        return flat.joined(separator: "\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in Swift, explained

    Problem overview

    The real cat accepts several files and prints them one after another. In this version each "file" is an array of lines, so the input is an array of arrays: concatCat(_ allLines: [[String]]) -> String. The function puts all the lines in order, from the first file's first line to the last file's last line, and joins them with newlines.

    For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". Printed, it is five lines. A file can be empty and add no lines, and with no files at all the result is the empty string.

    Approach

    There are two jobs: flatten the nested arrays into a single array of lines, then join that array. The second job is the same joined(separator:) call as in the first version of cat. The first is a loop inside a loop: the outer loop visits each file and the inner loop visits each line of that file, appending it to one flat array.

    Doing the join once at the end, rather than adding newlines while looping, keeps the newline rule simple. A newline appears between two lines and never at the ends, and joined guarantees that however many files are empty. A file with no lines never enters the inner loop, so it contributes nothing, not even an extra separator.

    Step by step

    1. Create var flat: [String] = [], an empty array of strings. It will hold every line of every file, in order. The type annotation is needed because an empty literal gives Swift nothing to infer the element type from.
    2. Loop over the files with for fileLines in allLines. Each fileLines is itself a [String].
    3. Loop over that file's lines with for line in fileLines, inside the first loop.
    4. Append the line to flat with flat.append(line). Because the outer loop goes through the files in order and the inner loop goes through each file's lines in order, the lines end up in the right order.
    5. Return the joined array after both loops: flat.joined(separator: "\n").

    The solution in Swift

    class Solution {
        func concatCat(_ allLines: [[String]]) -> String {
            var flat: [String] = []
            for fileLines in allLines {
                for line in fileLines {
                    flat.append(line)
                }
            }
            return flat.joined(separator: "\n")
        }
    }
    

    Swift details worth a closer look:

    • for ... in needs no indices. The loop variable takes each element directly, so there is no index arithmetic to get wrong.
    • Loop variables are constants. fileLines and line can be read but not assigned to inside the loops.
    • flat is a var. append changes the array, and Swift only allows that on a var. Declaring it with let would be a compile error.
    • A shorter form exists. allLines.flatMap { $0 } produces the same flat array in one expression. Writing the loops out makes the flattening visible, which is the point of this lesson.

    Complexity

    Every line is visited once and appended to flat, and appending to an array is constant time on average. The final join copies each character once. Time is proportional to the total size of the input. The extra space is the flat array and the result string, also proportional to the total size.

    Edge cases and common mistakes

    • Empty files. [["a"], [], ["b"]] gives "a\nb". The empty file adds no line and no newline.
    • No files. [] and [[], []] both give "".
    • Blank lines are lines. A file that holds [""] has one line, which is blank. So [[""], [""]] gives "\n": two blank lines with a newline between them.
    • Joining each file separately. Joining every file on its own and then joining those strings with newlines breaks on an empty file: its empty string still gets separators around it, so [["a"], [], ["b"]] would give "a\n\nb". Flattening first avoids that.
    • A trailing newline. Adding "\n" after every line would end the result with a newline that the lesson doesn't expect.

    Testing

    InputResult (as a Swift literal)
    [["hello", "world"], ["foo", "bar", "baz"]]"hello\nworld\nfoo\nbar\nbaz"
    [["a"], [], ["b"]]"a\nb"
    [[""], [""]]"\n"
    []""
    [[], []]""
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free