[英]How can I generate a random unicode character in Swift?
My current attempts at creating a random unicode character generate have failed with errors such as those mentioned in my other question here . 我目前尝试创建随机unicode字符生成的尝试失败,但出现了错误,例如我在此其他问题中提到的那些错误。 It's obviously not as simple as just generating a random number.
显然,它不像生成随机数那样简单。
Question: How can I generate a random unicode character in Swift? 问题:如何在Swift中生成随机的Unicode字符?
Unicode Scalar Value Unicode标量值
Any Unicode code point except high-surrogate and low-surrogate code points.
除高代理和低代理代码点外的任何Unicode代码点。 In other words, the ranges of integers 0 to D7FF and E000 to 10FFFF inclusive.
换句话说,整数范围为0到D7FF和E000到10FFFF。
So, I've made a small code's snippet. 因此,我编写了一个小代码段。 See below.
见下文。
func randomUnicodeCharacter() -> String {
let i = arc4random_uniform(1114111)
return (i > 55295 && i < 57344) ? randomUnicodeCharacter() : String(UnicodeScalar(i))
}
randomUnicodeCharacter()
let N: UInt32 = 65536
let i = arc4random_uniform(N)
var c = String(UnicodeScalar(i))
print(c, appendNewline: false)
I was a little bit confused with this and this . 我是一个有点困惑这个和这个 。 [Maximum value: 65535]
[最大值:65535]
static func randomCharacters(withLength length: Int = 20) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.characters.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
Here you can modify length (Int) and use this for generating random characters. 在这里,您可以修改长度(Int)并将其用于生成随机字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.