Start learning free

LESSON 379 OF 415 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v2 — First n Lines in Swift

Practice

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.count. If n is 0 the result is the empty string.

Function signature:

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

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Use the slice lines[0..<n] for the first n elements, then joined(separator: "\n"). Since the problem guarantees n ≤ lines.count, no min needed.

Combine the slice and join into one expression:
return lines[0..<n].joined(separator: "\n")


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

STEP 1 OF 1
    Ctrl + Enter to check

    Head V2 in Swift

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