Escaping backslash in Swift

Swift 5 version

let originalString = "1\\2"
print("originalString: \(originalString)")
let newString = originalString.replacingOccurrences(of: "\\", with: "\\\\")
print("newString: \(newString)")
replacingOccurrences(of: "\\", with: "\\\\")

Output:

originalString: 1\2  
newString: 1\\2  

The double backslash exists only in your code, it is a convention of the compiler. It never exists in the string itself, just in the Swift code.

If you want a double backslash in the string you need to have four backslashes in your code. Or use a String method to replace single backslashes with double backslashes.

Code example:

let originalString = "1\\2"
print("originalString: \(originalString)")
let newString = originalString.stringByReplacingOccurrencesOfString("\\", withString: "\\\\", options: .LiteralSearch, range: nil)
print("newString: \(newString)")

Output:

originalString: 1\2  
newString: 1\\2