I need to create function that will change several elements in 1 string
Without declaring this as a function – it work properly, but in the function it changing only 1 random char
can u help me pls
import Foundation
func makeItCool(_ string: String) -> String {
var newCoolString = string
let replaces = [
"a" : "@",
"o" : "0",
"t" : "+",
"i" : "1",
"s" : "$",
]
for (key, value) in replaces {
newCoolString = string.lowercased().replacingOccurrences(of: key, with: value)
}
return newCoolString
}
print(makeItCool("Swift is Awesame"))
//sw1ft 1s awesame
Working code
var string = "Swift is Awesaome"
let replaces = [
"a" : "@",
"o" : "0",
"t" : "+",
"i" : "1",
"s" : "$",
]
for (key, value) in replaces {
string = string.lowercased().replacingOccurrences(of: key, with: value)
}
print(string)
// $w1f+ 1$ @we$@0me
3
Answers
In the working example you are iteratively updating the same string, so the effects of the replacements are cumulative.
In the failing version you are always applying the transformation to the original method parameter
string
so each time through the for loop you will overwrite the previous changes, and will just return the changes from the final iteration.I’m sure you meant to write:
although a more efficient approach would be to
I think the problem is in this line
You should replace occurrences in newCoolString like this: