Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

ios - Random Password Generator Swift 3?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...