I'm very new to swift and I'm trying to write a simple regex app that takes user input of a file path and applies several regex replacements to the text file.
import Foundation
let shotFilePath = readLine()
// Use contentsOfFile overload.
// ... Specify utf8 encoding.
// ... Ignore errors.
let babySteps = try NSString(contentsOfFile: shotFilePath!,
encoding: String.Encoding.utf8.rawValue)
let firetruck = #"Ay Ay Sir!"#
var firetruckYou = babySteps.replacingOccurrences(of: firetruck, with: "", options: .regularExpression)
The problem is something with the last line of code. With a hardcoded string everything works however when I allow it to be entered by a user I get the following error:
If I hardcode the babySteps string in a constant, no issue, but if I have it be imported from a file, things turn sour.
What is causing Swift to behave differently in the two instances? Many thanks in advance!
I don't know why the guy that originally posted this deleted his answer, but here was his very elegant solution:
let babySteps = try String(contentsOfFile: shotFilePath!, encoding: .utf8)
Thanks to Mojtaba who later pointed out the difference between String and NSString as well!