LoginSignup
14
13

More than 5 years have passed since last update.

Swiftでランダム英数字の文字列生成(※arc4random()は使ってはいけない)

Last updated at Posted at 2016-07-06

SwiftでセッションIDなど、桁数を指定してランダム英数字を生成させたい時

ポイント

arc4random()ではなく、arc4random_uniform(UInt32)を使用するのがポイント

arc4random()を使うとクラッシュする

arc4random()は乱数を生成させる関数ですが、Intにキャストする際に32bit端末ではクラッシュします。iPhone5や4Sなど、初代iPad Air以前は32bit

arc4randomはunsigned 32 bit integerを返しますが、つまり0から4,294,967,295まで。
IntはiPhone5で32ビットの整数と5S上の64ビット整数です。arc4random()はiPhone5上のIntの倍の正の範囲を持っているUInt32型を返すので、クラッシュする可能性が50%あります。

また詳細は記述しませんが、ランダム性に少しバイアスがあるarc4random()のずれを補正し、int型に変換しても安全なのがarc4random_uniform()です。

実装

引数の数だけ、a-zの小文字大文字、0-9を組み合わせた文字列を生成します。
arc4random_uniformを使用

    func generate(length: Int) -> String {
        let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var randomString: String = ""

        for _ in 0..<length {
            let randomValue = arc4random_uniform(UInt32(base.characters.count))
            randomString += "\(base[base.startIndex.advancedBy(Int(randomValue))])"
        }
        return randomString
    }

// 32桁の乱数を生成
print(generate(32))
// 14832cfdd506508a8c788340f5ac618bb234d5f7bd3f3dbf902fd04ac9896fe8

参照

Generate random alphanumeric string in Swift
http://stackoverflow.com/questions/26845307/generate-random-alphanumeric-string-in-swift

Objective-Cの乱数作成はarc4random_uniform
http://tanukichi566.blog.fc2.com/blog-entry-57.html

arc4randomの罠
http://qiita.com/jtemplej/items/abebac88f930f9345f95

[Swift][iOS]64bit対応におけるarc4random()について
http://qiita.com/kiguchi/items/c75d6d3da05b3e8d80d9

14
13
2

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
14
13