Created
August 12, 2015 13:53
-
-
Save skreutzberger/eac3edc7918d0251f366 to your computer and use it in GitHub Desktop.
generate random text in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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