Skip to content

Comment on Swift Blogparent

Comments

To get the number of characters in a string, call countElements(string). To generate a random character, your best bet (IMO, someone else may have a more elegant solution) is to have an array (or dictionary) or characters and use a random number generator to select a character from the structure.

It would be easier to do this from an array of strings but I found an ugly inefficient way to do it from the characters in an arbitrary string:

  func randChar(alphabet:String?)->String {
    let alpha = alphabet ? alphabet! : "abcdefghijklmnopqrstuvwxyz"
    let rand:Int = Int(arc4random_uniform(UInt32(countElements(alpha))))
    var gen = alpha.generate()
    for i in 0..<rand {
        gen.next()
    }
    return String(gen.next()!)
  }
mikeash obviously has the answer if the codepoints are consecutive.

This was quite annoying to do, more so than I expected. If you convert to UTF16 view you can alter the index by advanceBy but then I couldn't find an easy way to convert back from the UInt16 to a Character/String but mikeash also covers that. However I'm not sure that conversion to UTF16 is any less work internally than iterating through the index.

If you have a range of unicode code points that you want to select from, you can generate a random number in that range and then turn it into a one-character string like so:

    let codepoint: UInt32 = ...random choice code here...
    let scalar = UnicodeScalar(codepoint)
    let string = String(scalar)
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.