如何在 Swift 中生成随机 unicode 字符?

How can I generate a random unicode character in Swift?

我目前尝试创建一个随机 unicode 字符生成失败,出现了我在另一个问题 中提到的错误。显然不是生成随机数那么简单

问题:如何在Swift中生成一个随机的unicode字符?

Unicode Scalar Value

Any Unicode code point except high-surrogate and low-surrogate code points. In other words, the ranges of integers 0 to D7FF and E000 to 10FFFF inclusive.

所以,我制作了一小段代码。见下文。

此代码有效

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)

我对 this and this 有点困惑。 [最大值: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
}

在这里您可以修改长度(Int)并使用它来生成随机字符。