How can I generate a random unicode character in S

2019-03-04 13:20发布

问题:

My current attempts at creating a random unicode character generate have failed with errors such as those mentioned in my other question here. It's obviously not as simple as just generating a random number.

Question: How can I generate a random unicode character in Swift?

回答1:

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.

So, I've made a small code's snippet. See below.

This code works

func randomUnicodeCharacter() -> String {
    let i = arc4random_uniform(1114111)
    return (i > 55295 && i < 57344) ? randomUnicodeCharacter() : String(UnicodeScalar(i))
}
randomUnicodeCharacter()

This code doesn't work!

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]



回答2:

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.