Start learning free

LESSON 5 OF 71 · PROJECTS: COMMAND-LINE TOOLS

head in Swift: First 10 Lines with min and ArraySlice

Practice Read the full explanation

Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.

Function signature:

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

Example:

Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"

When printed:
a
b
c
d
e
f
g
h
i
j

Use a range slice to grab the first 10 lines, but cap the upper bound at lines.count when the array is shorter than 10. Then call joined(separator: "\n") on the slice.

Compute let end = min(10, lines.count), then slice lines[0..<end].

The full solution:
class Solution {
    func head(_ lines: [String]) -> String {
        let end = min(10, lines.count)
        return lines[0..<end].joined(separator: "\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Head V1 in Swift, explained

    Problem overview

    The Unix head command shows the beginning of a file, ten lines by default. The function head(_ lines: [String]) -> String takes an array of lines and returns the first 10, joined by newline characters. With fewer than 10 lines it returns all of them, and with no lines it returns the empty string.

    With the thirteen lines "a" to "m" the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj", which prints as the letters a to j, one per line. With only ["x", "y", "z"] the result is "x\ny\nz", and with [] it is "".

    Approach

    The task has two parts: choose how many lines to keep, then join them. The number to keep is 10 unless the array is shorter, which is exactly min(10, lines.count).

    That count is what makes the slice safe. Asking for lines[0..<10] on an array of three elements crashes, because the range reaches past the end. Capping the upper bound with min means the range never asks for lines that aren't there, and the same code handles 13 lines, 3 lines and none.

    Step by step

    1. Compute the end of the range as let end = min(10, lines.count). With 13 lines it is 10; with 3 lines it is 3; with none it is 0. min is a global function that returns the smaller of two values.
    2. Slice and join. lines[0..<end] selects the items from index 0 up to but not including end, and joined(separator: "\n") glues them with a newline between each two. The result has no newline after the last line.

    The solution in Swift

        func head(_ lines: [String]) -> String {
            let end = min(10, lines.count)
            return lines[0..<end].joined(separator: "\n")
        }
    

    Swift details worth a closer look:

    • A range subscript gives an ArraySlice, not an array. lines[0..<end] has type ArraySlice<String>: a view onto part of the original array. joined(separator:) works on a slice as it does on an array, so no conversion is needed here.
    • The half-open range. 0..<end excludes end, so it holds exactly end positions. The closed range 0...end would include one too many, and would crash when end equals the count.
    • An empty range is fine. 0..<0 is valid and selects nothing, so an empty array needs no special case. Joining no strings gives "".
    • end is just a name. It isn't reserved in Swift. The constant is declared with let because it is never changed after being set.

    Complexity

    At most 10 lines are joined, so the join takes time proportional to the total length of those lines and doesn't depend on how many lines the input holds. The slice shares the original array's storage rather than copying it. Extra space is the output string.

    Edge cases and common mistakes

    • Fewer than 10 lines. Without the min, the slice lines[0..<10] on a short array crashes the program with an out-of-range error.
    • Exactly 10 lines. min(10, 10) is 10 and all ten lines come back. Ten lines give the same result as the first ten of a longer array.
    • Empty input. The result is "".
    • Off by one. Writing 0...end or min(9, lines.count) returns 11 or 9 lines instead of 10.
    • A trailing newline. The newline belongs between lines. Adding one after the last line gives output that doesn't match the lesson's expected strings.

    Testing

    InputResult (as a Swift literal)
    thirteen lines, "a" to "m""a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    ["x", "y", "z"]"x\ny\nz"
    []""
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free