Random Password Generator Swift 3?

半城伤御伤魂 提交于 2020-12-23 06:50:37

问题


I'm building a random password generator for iOS. In it, a button generates a random password that has characteristics chosen by the user (e.g. switches to turn on or off lowercase and uppercase letters, characters and symbols, and so on).

The UI looks great, the rest of the code is working smoothly, but I can't get my button to actually generate a random alphanumerical string. I have a label with some placeholder text ("Your Password") that should have its text updated to a random string when the button is pushed, but I am getting a compiler error: "unresolved use of identifier 'length'"

Here is the current code for the button:

@IBAction func generatePassword(_ sender: UIButton) {

    let randomPasswordArray: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    let len = UInt32(randomPasswordArray.length)

    var randomPassword = ""

    for _ in 0 ..< length {
        let rand = arc4random(len)
        var nextChar = randomPasswordArray.character(at: Int(rand))
        randomPassword += NSString(characters: &nextChar, length: 1) as String
    }

    passwordLabel.text = "randomPassword"
}

Thanks!


回答1:


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\n"

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\n"



回答2:


Your code should be

...
for _ in 0 ..< len {
...



回答3:


You can also use

import Security

let password = SecCreateSharedWebCredentialPassword() as String?
print(password)


来源:https://stackoverflow.com/questions/41730933/random-password-generator-swift-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!