I don’t believe in making folks wait, so here’s the simple answer: if you’re using the
String method replacingOccurrences(of:with) you should probably change it to replacing(_:with:) to avoid causing unintentional and frankly bizarre bugs.If you’re not sure why, read on – I’ll start by showing you the problem in a simple way, then show you the solution.
First, think about this code:
let vacation = "🇨🇦🇺🇸"That’s a trivial string containing two flags. As it’s a string, we can check whether it contains the Canadian flag like this:print(vacation.contains("🇨🇦"))And we can check whether the string includes the US flag like this:print(vacation.contains("🇺🇸"))Both those will print true, because both those flags are present in the string.Similarly, we could check whether the string contains the Australian flag like this:
print(vacation.contains("🇦🇺"))That will print false, because clearly the string "🇨🇦🇺🇸" does not contain 🇦🇺.Now try this:
print(vacation.replacingOccurrences(of: "🇦🇺", with: "🇳🇮"))That replaces the Australian flag with the Nicaraguan flag, which sounds innocent but is at the core of the problem I’m talking about here.If you’re reading this and not trying the code, this will hurt your head: that code will print “🇨🇳🇮🇸” – the flags for China and Iceland.
Yes, even though we’re replacing something that doesn’t exist in the string.
What’s happening here?
Problem, meet solution
The problem is that `replacingOccurrences(of:wi...https://www.hackingwithswift.com/articles/280/one-swift-mistake-everyone-should-stop-making-today
