Generate random alphanumeric string in Swift

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

How can I generate a random alphanumeric string in Swift?

22条回答
  •  青春惊慌失措
    2020-11-27 10:12

    Here's a ready-to-use solution in Swiftier syntax. You can simply copy and paste it:

    func randomAlphaNumericString(length: Int) -> String {
        let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let allowedCharsCount = UInt32(allowedChars.characters.count)
        var randomString = ""
    
        for _ in 0 ..< length {
            let randomNum = Int(arc4random_uniform(allowedCharsCount))
            let randomIndex = allowedChars.index(allowedChars.startIndex, offsetBy: randomNum)
            let newCharacter = allowedChars[randomIndex]
            randomString += String(newCharacter)
        }
    
        return randomString
    }
    

    If you prefer a Framework that also has some more handy features then feel free to checkout my project HandySwift. It also includes a beautiful solution for random alphanumeric strings:

    String(randomWithLength: 8, allowedCharactersType: .alphaNumeric) // => "2TgM5sUG"
    

提交回复
热议问题