Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

swift function for char in string changing trouble

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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:

for (key, value) in replaces {
    newCoolString = newCoolString().lowercased().replacingOccurrences(of: key, with: value)
}

although a more efficient approach would be to

let newCoolString = string.lowercased()

//...

for (key, value) in replaces {
    newCoolString = newCoolString().replacingOccurrences(of: key, with: value)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading