First create an array with your password allowed characters
let passwordCharacters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".characters)
then choose the password lenght
let len = 8
define and empty string password
var password = ""
create a loop to gennerate your random characters
for _ in 0..<len {
// generate a random index based on your array of characters count
let rand = arc4random_uniform(UInt32(passwordCharacters.count))
// append the random character to your string
password.append(passwordCharacters[Int(rand)])
}
print(password) // "V3VPk5LE"
Swift 4
You can also use map instead of a standard loop:
let pswdChars = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
let rndPswd = String((0..<len).map{ _ in pswdChars[Int(arc4random_uniform(UInt32(pswdChars.count)))]})
print(rndPswd) // "oLS1w3bK
"
Swift 4.2
Using the new Collection's randomElement()
method:
let len = 8
let pswdChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
let rndPswd = String((0..<len).compactMap{ _ in pswdChars.randomElement() })
print(rndPswd) // "3NRQHoiA
"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…