LoginSignup
9
3

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-09-10

本体


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

9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3