Skip to content

Instantly share code, notes, and snippets.

@skreutzberger
Created August 12, 2015 13:53
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skreutzberger/eac3edc7918d0251f366 to your computer and use it in GitHub Desktop.
Save skreutzberger/eac3edc7918d0251f366 to your computer and use it in GitHub Desktop.
generate random text in Swift
// returns random text of a defined length
// optional bool parameter justLowerCase
// to just generate random lowercase text
func randomText(length: Int, justLowerCase: Bool = false) -> String {
var text = ""
for _ in 1...length {
var decValue = 0 // ascii decimal value of a character
var charType = 3 // default is lowercase
if justLowerCase == false {
// randomize the character type
charType = Int(arc4random_uniform(4))
}
switch charType {
case 1: // digit: random Int between 48 and 57
decValue = Int(arc4random_uniform(10)) + 48
case 2: // uppercase letter
decValue = Int(arc4random_uniform(26)) + 65
case 3: // lowercase letter
decValue = Int(arc4random_uniform(26)) + 97
default: // space character
decValue = 32
}
// get ASCII character from random decimal value
let char = String(UnicodeScalar(decValue))
text = text + char
// remove double spaces
text = text.stringByReplacingOccurrencesOfString(" ", withString: " ")
}
return text
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment