Problem overview
The first version of head always returned up to 10 lines. This version adds the count as a parameter: head(_ lines: [String], _ n: Int) -> String returns the first n lines joined by newline characters. For this version you may assume 0 <= n <= lines.count. When n is 0 the result is the empty string.
For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3 the result is "alpha\nbeta\ngamma". Printed, those are three lines.
Approach
The function from the previous version computed how many lines to keep. Here the caller supplies that number, and the promise that it lies between 0 and the number of lines means the function can use it directly as the end of the range. There is nothing to compute, so the body is a slice and a join.
The next version builds on this one by relaxing the assumption.
Step by step
- Slice and join in one return.
lines[0..<n]selects the firstnitems, from index 0 up to but not including indexn. Callingjoined(separator: "\n")on that slice puts a newline between each two lines and none at the end.
The solution in Swift
func head(_ lines: [String], _ n: Int) -> String {
return lines[0..<n].joined(separator: "\n")
}
Swift details worth a closer look:
- The unlabeled parameters. Both parameters have an underscore in front, so a call looks like
head(lines, 3), nothead(lines, n: 3). The first_hides the label oflinesand the second does the same forn. - The half-open range
0..<ncontains exactlynpositions, so it selectsnlines. Forn = 0it is the empty range0..<0, a valid range that selects nothing, and joining nothing gives"". - The result of the subscript is an
ArraySlice. It keeps the indices of the original array. A slice taken from positions 2 up to 4 hasstartIndex2 andendIndex4, and its first element is read withslice[2], notslice[0]. Here the slice starts at 0, so the difference doesn't show, andjoineddoesn't use indices anyway. - Invalid ranges crash. Swift checks the range at run time. An
nlarger thanlines.countstops the program with a fatal error, and so does a negativen, because the range0..<nwould then have its upper bound below its lower bound. The assumption in the statement is what keeps this function safe.
Complexity
The function joins n lines, so the time is proportional to the total length of those lines. The slice itself isn't a copy, and the only new memory is the result string.
Edge cases and common mistakes
n = 0. The result is"", not a string holding a newline.head(lines, 0)works without a special case.nequal to the count. Every line is returned.head(["a", "b"], 2)is"a\nb".- Using a closed range.
lines[0...n]returnsn + 1lines and crashes whennequals the count. - Joining with a trailing newline. The separator goes between lines only, so the result never ends with
\n.
Testing
| Input | Result (as a Swift literal) |
|---|---|
["alpha", "beta", "gamma", "delta", "epsilon"], n = 3 | "alpha\nbeta\ngamma" |
the same lines, n = 0 | "" |
the same lines, n = 5 | "alpha\nbeta\ngamma\ndelta\nepsilon" |
