Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: