String replacing occurrences

I am facing a weird issue with Swift +4.0 String. Here is a breakdown of the issue.

Let's assume we have a string:

Here, we have 4 [BACKSLASH]s in our String. Our task is to replace each occurrence of [BACKSLASH] with a real backslash \.

We start by figuring out how we will implement this in our AwesomePlayground.playground:

ourStr = ourStr.replacingOccurrences(of: "[BACKSLASH]", with: "\\")
print(ourStr) // prints @p@P|Bl@\Fbk@XO\d@V\\c@

Works great, let's implement this in our AwesomeProject.xcodeproj

ourStr = ourStr.replacingOccurrences(of: "[BACKSLASH]", with: "\\")
print(ourStr) // prints @p@P|Bl@\\Fbk@XO\\d@V\\\\c@

This is completely unexpected! We just test this out in the playground and it's working perfectly fine!
In the xcodeproj it replaced the [BACKSLASH] with 2 backslashes, while in the playground it knows that one is escaping character.

I solved it by using NSString replacingOccurrences method. But, I believe there is something wrong going there.

Which version of Swift and/or Xcode are you using? I get the same result whether in a Playground or in a compiled app.

I tried on Xcode Version 9.2 and Xcode Version 9.3

Is ourStr at fault, or the print output? (What is the value of ourStr.count in each case?)

The unerlying string data is the same. It's 'just' a matter of how it is presented by Xcode in the console output here and there. I would suggest filing a bug against Xcode. It's not a Swift issue in itself.

I cannot reproduce this effect in Xcode 9.3b4 with the default toolchain. After running the Xcode project, I see:

Program ended with exit code: 0
1 Like

You're right! I tried that out with both, it should the same count for both cases.

You're right! It's Xcode bug, not Swift.
Thank you for your help.