skip to Main Content

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


  1. 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)
    }
    
    Login or Signup to reply.
  2. func makeItCool(_ string: String) -> String {
        var newCoolString = string.lowercased()
        let replaces = [
            "a" : "@",
            "o" : "0",
            "t" : "+",
            "i" : "1",
            "s" : "$",
        ]
        
        for (key, value) in replaces {
            newCoolString = newCoolString.replacingOccurrences(of: key, with: value)
        }
        return newCoolString
    }
    print(makeItCool("Swift is Awesame"))
    
    Login or Signup to reply.
  3. I think the problem is in this line

    newCoolString = string.lowercased().replacingOccurrences(of: key, with: value)
    

    You should replace occurrences in newCoolString like this:

    newCoolString = newCoolString.lowercased().replacingOccurrences(of: key, with: value)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search