Start learning free

LESSON 1 OF 71 · PROJECTS: COMMAND-LINE TOOLS

cat in Swift: Joining Lines with joined(separator:)

Practice Read the full explanation

Build a tiny version of the Unix cat command. Given a list of lines, return them joined by newline characters (\n) so they print one per line.

Lines can be blank, and the list can be empty (the result is then an empty string).

Function signature:

func cat(_ lines: [String]) -> String

Example:

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

Output: "hello\nworld\nfoo"

When printed:
hello
world
foo

Think of the output as one big String where each input line is separated from the next by a newline character. Swift's Array has a method that glues all of its elements together with a chosen separator.

Call lines.joined(separator: "\n") — the separator goes between every pair of lines.

The full solution is a one-liner:
class Solution {
    func cat(_ lines: [String]) -> String {
        return lines.joined(separator: "\n")
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Cat V1 in Swift, explained

    Problem overview

    The Unix cat command prints text one line after another. This first version takes an array of strings and returns a single string in which the lines are separated by newline characters: func cat(_ lines: [String]) -> String. Lines may be blank, and an empty array gives an empty string.

    For ["hello", "world", "foo"] the result is the string "hello\nworld\nfoo". Printed, it appears as three lines. Notice that there is no newline after foo: a newline goes between two lines, not after each one.

    Approach

    The Swift literal "\n" is a single newline character, not the two characters backslash and n. That is why printing the result breaks the line instead of showing the backslash.

    Gluing items together with a separator between them is common enough that Swift has a method for it. joined(separator:) is available on a sequence of strings. It places the separator between each pair of neighbours and nowhere else, which is the exact behaviour the lesson needs.

    The alternative is a loop that appends each line and a newline:

    var out = ""
    for line in ["x", "y"] { out += line + "\n" }
    

    This leaves out equal to "x\ny\n", one newline too many at the end, which you would then have to remove. Letting joined handle the boundary avoids that off-by-one trap.

    Step by step

    1. Return lines.joined(separator: "\n"). The separator is the one-character string "\n", the escape for a newline. The result is already the String the signature promises.

    The solution in Swift

        func cat(_ lines: [String]) -> String {
            return lines.joined(separator: "\n")
        }
    

    Details worth knowing:

    • The label is required. The argument is written separator: "\n". Calling joined("\n") fails with "missing argument label 'separator:' in call".
    • The separator has a default. joined() with no argument glues the strings together with nothing between them: ["a", "b"].joined() is "ab".
    • The input array isn't changed. joined builds a new string and leaves lines as it was.

    Complexity

    Time and space are both proportional to the total number of characters across all lines, plus one character per separator: the method visits each line once and builds one new string of that size. The number of lines alone isn't the whole story, since long lines cost more than short ones.

    Edge cases and common mistakes

    • An empty array. There are no neighbours, so no separator is placed and the result is "". No special case is needed.
    • One line. The result is that line unchanged, with no newline added.
    • Blank lines are real entries. ["a", "", "b"] becomes "a\n\nb": two newlines in a row, which is how a blank line looks in text. The array [""] gives "", but ["", ""] gives "\n", because the blank lines are separated by one newline.
    • Don't add a final newline. The lesson's expected output ends right after the last line, so a loop that appends "\n" after every line fails the lesson's tests.

    Testing

    These inputs show the behaviour at the boundaries:

    InputResult (as a Swift literal)
    ["hello", "world", "foo"]"hello\nworld\nfoo"
    ["a", "", "b"]"a\n\nb"
    ["", ""]"\n"
    [""]""
    []""

    Printing the first result with print shows the three lines on separate rows, since print turns each \n into a line break.

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