0

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?

Community
  • 1
  • 1
Vatsal Manot
  • 17,695
  • 9
  • 44
  • 80
  • It should be possible roughly like this: 1. find a random number from the Unicode range you want the character to be in 2. [get the character corresponding with that number](http://sketchytech.blogspot.com.es/2014/10/playing-with-primitives-characters.html) – Pekka Aug 22 '15 at 14:57

2 Answers2

3

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]

Tikhonov Aleksandr
  • 13,945
  • 6
  • 39
  • 53
0
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.

tBug
  • 789
  • 9
  • 13