Tel Tel - 5 months ago 8
Swift Question

How to randomize the case of letters in a string in Swift?

Given a string, I would like to change the case of each letter to a random between upper and lower case.

For example:

let myString = "Have a nice day!"
let newString = "haVe A NiCe dAY!"

Answer

I would use arc4random_uniform and map like this:

let myString = "Have a nice day!"

let result = myString.characters.map { (char) -> String in
    if arc4random_uniform(2) == 0 {
        return String(char).lowercaseString
    }
    return String(char).uppercaseString
}.joinWithSeparator("")

print(result)

hAvE A NICe DAy!

Comments