Edited at

【Swift3】ランダムな英数字を生成する方法(桁数指定可)

More than 1 year has passed since last update.


本体


func randomString(length: Int) -> String {

let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)

var randomString = ""

for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}

return randomString
}


使い方

let randomString = randomString(length: 10) // 10桁のランダムな英数字を生成

print(randomString)


参考

Generate random alphanumeric string in Swift - Stack Overflow