Swift Code Example using map inside of forEach

This looks like it should work but it doesn't:

let str = "SOME SEARCH TEXT"
var thing = String()
let letters = ["A","E","S"]
let replacements = ["a", "e", "s"]

 letters.enumerated().forEach { (i,r) in   
        thing = String(str.map {$0 == Character(String(r)) ? Character(String(replacements[i])) : $0});
    print(thing)
}

I want the looped changes to persist but only the last iteration does. Any ideas?

TIA, SC

Is this homework?

Only the last iteration of thing persists because it is recreated on each iteration of i. Change the initialisation of thing to be str, i.e. to "SOME SEARCH TEXT" and the reference to str.map to be thing.map and it will work:

let str = "SOME SEARCH TEXT"
var thing  = str
let letters = ["A","E","S"]
let replacements = ["a", "e", "s"]

 letters.enumerated().forEach { (i,r) in
        thing = String(thing.map {$0 == Character(String(r)) ? Character(String(replacements[i])) : $0});
    print(thing)
}

If it's OK to have str mutate, then you can change str to a var and then use this code:

var str = "SOME SEARCH TEXT"
let letters = ["A","E","S"]
let replacements = ["a", "e", "s"]

 letters.enumerated().forEach { (i,r) in
        str = String(str.map {$0 == Character(String(r)) ? Character(String(replacements[i])) : $0});
    print(str)
}

Best wishes and regards, Michaela

Thanks for the reply! I do need to preserve 'str' so I guess I need:

let str = "SOME SEARCH TEXT"
var tmpStr = str
let letters = ["A","E","S"]
let replacements = ["a", "e", "s"]


 letters.enumerated().forEach { (i,r) in   
        tmpStr = String(tmpStr.map {$0 == Character(String(r)) ? Character(String(replacements[i])) : $0});
    print(tmpStr)
}

LOL! I wish I was that young. I'm just playing around with Swift5 and Xcode 11 on a 10 year old iMac. If you know, when I access the "Help" menu in my app it gives out a boilerplate message that I'd like to replace (this is importing Cocoa and using the Storyboard for macOS).

(sorry for the late reply)

TIA, SC

Swift Code Example using map inside of forEach
 
 
Q