给定一个字符串,我想将每个字母的大小写改为大小写之间的随机字符。
例如:
{
"presets": ["es2015", "stage-1", "react"]
}
答案 0 :(得分:7)
Swift 2
我会使用arc4random_uniform
和map
。
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: "")