Problem overview
The second version of the grep project adds the -i flag. The function grepCaseInsensitive(_ lines: [String], _ pattern: String) -> String returns every line that contains the pattern as a substring, ignoring letter case, joined by newline characters. The lines that come back keep their original casing, and if nothing matches the result is the empty string. The lines contain only ASCII characters.
With pattern = "ERR" and lines = ["Error: 1", "ok"], the first line matches even though its letters are Err and not ERR, and the result is "Error: 1". The second line has no err in any casing.
Approach
Version 1 compared the line and the pattern exactly. To ignore case, make both sides the same case before comparing. Converting to lowercase is the usual choice: "Error" becomes "error", "ERR" becomes "err", and the plain contains check then finds the match.
The conversion is only for the test. What goes into the result is the original line, so a matching "Error: 1" is returned as written and not as "error: 1".
The pattern is the same for every line, so it needs lowercasing just once, before the loop. Doing it inside the loop would give the same answers but repeat the work for every line. The lines differ from one another, so each one is lowercased on its own turn.
Step by step
- Create an empty array of strings named
resultwithvar, to collect the matching lines. - Lowercase the pattern once into a
letnamedlowerPattern, usingpattern.lowercased(). It never changes, soletfits. - Loop over the lines with
for line in lines, writing the closing brace right away. - Test a lowercase copy of the line. Start an
ifonline.lowercased().contains(lowerPattern). Both sides are lowercase, soERRfindsError. The line itself isn't changed. - Append the original line to
result, capitals and all. - Join and return with
result.joined(separator: "\n"). An emptyresultgives the empty string.
The solution in Swift
func grepCaseInsensitive(_ lines: [String], _ pattern: String) -> String {
var result = [String]()
let lowerPattern = pattern.lowercased()
for line in lines {
if line.lowercased().contains(lowerPattern) {
result.append(line)
}
}
return result.joined(separator: "\n")
}
The details a learner might trip on:
lowercased()returns a new string. Strings are values in Swift, so the call doesn't modifylineorpattern. That is why appendinglineafterwards still gives the original text.- Method, not property. It is
lowercased()with parentheses and a trailingd. The shorter-lookinglowercasedoesn't exist onString. - Appending the wrong thing.
result.append(line.lowercased())would compile and run, but the output would lose the original casing, and the lesson's tests would fail on lines like"Error: 1". - ASCII only. Case conversion is simple for ASCII letters. For other alphabets the rules are more complicated, and this lesson avoids them by keeping the input to ASCII.
Complexity
Each line is lowercased once, which costs time proportional to its length, and then searched. The total time is proportional to the number of characters in all lines, times the pattern length in the worst case for the substring search. Extra space is the lowercase copy of one line at a time, plus the array of kept lines and the joined result.
Edge cases and common mistakes
- Casing in the output.
["Error", "eRROR", "fine"]with the pattern"error"returns"Error\neRROR", each line exactly as it came in. - Lowercasing only one side. If the line is lowercased but not the pattern,
"ERR"never matches anything. - No match returns
"", as does an empty array of lines. - An empty pattern is not defined by the statement. With Foundation imported,
contains("")isfalsein Swift, so nothing is returned. - A trailing newline. Build the output with
joined(separator:)and not by appending"\n"to each line.
Testing
| lines | pattern | Result |
|---|---|---|
["Error: 1", "ok"] | "ERR" | "Error: 1" |
["Error", "eRROR", "fine"] | "error" | "Error\neRROR" |
["ok"] | "ERR" | "" |
