如何随机化Swift中字符串中的字母大小写?

时间:2016-06-08 12:32:39

标签: string swift

给定一个字符串,我想将每个字母的大小写改为大小写之间的随机字符。

例如:

{
  "presets": ["es2015", "stage-1", "react"]
}

1 个答案:

答案 0 :(得分:7)

Swift 2

我会使用arc4random_uniformmap

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!

Swift 3

let result = myString.characters.map {
    if arc4random_uniform(2) == 0 {
        return String($0).lowercased()
    }
    return String($0).uppercased()
}.joined(separator: "")

Swift 4.2

let result = myString.map {
    if Int.random(in: 0...1) == 0 {
        return String($0).lowercased()
    }
    return String($0).uppercased()
}.joined(separator: "")