Problem overview
The first version of the tr tool swaps one character for another. tr(_ lines: [String], _ fromChar: String, _ toChar: String) -> String replaces every fromChar with toChar in each line and returns the lines joined with "\n". Both arguments are single ASCII characters, taken literally, and case matters. A line may be empty or may not contain fromChar at all.
For ["banana", "apple"], "a" and "X" the result is "bXnXnX\nXpple".
Approach: translate each line, then join
The work is per line, and lines don't affect each other. Walk through the array, translate each line, collect the results in a new array, and join them at the end. Swift's replacingOccurrences(of:with:) does the translation in one call. It looks for the first string, replaces every match with the second and returns a new string. The original line is not modified.
Both parameters are typed String, even though they hold one character each. That matches what replacingOccurrences expects, so there is nothing to convert.
The loop could also be written with map, as lines.map { $0.replacingOccurrences(of: fromChar, with: toChar) }.joined(separator: "\n"), which gives the same "bXnXnX\nXpple" for the example. The explicit loop is easier to follow while you learn, and it matches the lesson's steps. Whichever you choose, the idea is the same: translate each line on its own, then join.
This tool is the smallest member of a family. The tr command in a shell translates characters read from its input, and this version handles only one pair of characters. The next version builds on it.
Step by step
- Create
resultas an empty[String]withvar. Each translated line is added to it. - Loop with
for line in lines. Eachlineis a whole line of text, not a single character. - Append the translated line with
line.replacingOccurrences(of: fromChar, with: toChar). It replaces all matches, not just the first. - Return
result.joined(separator: "\n")after the loop. It runs once, and the separator goes between lines only, so there is no newline after the last line.
The solution in Swift
func tr(_ lines: [String], _ fromChar: String, _ toChar: String) -> String {
var result = [String]()
for line in lines {
result.append(line.replacingOccurrences(of: fromChar, with: toChar))
}
return result.joined(separator: "\n")
}
Details that matter:
replacingOccurrencescomes from Foundation. It isn't part of the Swift standard library. In a file of your own, addimport Foundationat the top. Without it the compiler reportsvalue of type 'String' has no member 'replacingOccurrences'.- Strings are values. The method returns a new string, so
linekeeps its old text. That's why the result has to be stored:result.append(...)receives the new string. - Case matters. The search is exact, so
"Banana"with"b"and"X"stays"Banana". - Empty lines pass through. An empty line has nothing to replace, so it stays empty and still takes its place in the output.
[String](). It creates an empty array of strings;var result: [String] = []is an equivalent spelling.
Complexity
Time: O(total characters), since each line is scanned once for matches and copied once. Space: O(total characters) for the translated lines and the joined result.
Edge cases and common mistakes
- Lines without the character. They come out unchanged.
- Empty lines.
["banana", "", "cherry"]with"a"and"X"returns"bXnXnX\n\ncherry". The empty line becomes an empty piece between two newlines. - Empty input. An empty list returns
"". - Forgetting to use the return value. Calling
line.replacingOccurrences(...)without storing the result changes nothing, because strings are not modified in place. - Special characters. The characters are literal, so
"."is an ordinary dot here.["a.b.c"]with"."and"-"returns"a-b-c". - Trailing newline. Joining with
"\n"adds no newline after the last line.
Testing
["banana", "apple"],"a","X"gives"bXnXnX\nXpple".["banana", "", "cherry"],"a","X"gives"bXnXnX\n\ncherry".["Banana"],"b","X"gives"Banana".["a.b.c"],".","-"gives"a-b-c".[],"a","X"gives"".
