Generate random alphanumeric string in Swift

前端 未结 22 981
暖寄归人
暖寄归人 2020-11-27 09:51

How can I generate a random alphanumeric string in Swift?

22条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 10:04

    If your random string should be secure-random, use this:

    import Foundation
    import Security
    
    // ...
    
    private static func createAlphaNumericRandomString(length: Int) -> String? {
        // create random numbers from 0 to 63
        // use random numbers as index for accessing characters from the symbols string
        // this limit is chosen because it is close to the number of possible symbols A-Z, a-z, 0-9
        // so the error rate for invalid indices is low
        let randomNumberModulo: UInt8 = 64
    
        // indices greater than the length of the symbols string are invalid
        // invalid indices are skipped
        let symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    
        var alphaNumericRandomString = ""
    
        let maximumIndex = symbols.count - 1
    
        while alphaNumericRandomString.count != length {
            let bytesCount = 1
            var randomByte: UInt8 = 0
    
            guard errSecSuccess == SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomByte) else {
                return nil
            }
    
            let randomIndex = randomByte % randomNumberModulo
    
            // check if index exceeds symbols string length, then skip
            guard randomIndex <= maximumIndex else { continue }
    
            let symbolIndex = symbols.index(symbols.startIndex, offsetBy: Int(randomIndex))
            alphaNumericRandomString.append(symbols[symbolIndex])
        }
    
        return alphaNumericRandomString
    }
    

提交回复
热议问题