0

I am in the process of making one of my first apps, the aim of it is as a password generator and telling people on a scale of 1-1000 how hard it is to guess, and how hard it is to remember based on how the letters are formatted and what it looks like and how the brain remembers patterns. So far i have all the characters I want to use in an array, and I then have a for in loop that iterates through the characters, but I can't figure out how to specify the length of the password to generate, as currently it just prints each character. So, I am asking how can I make an 8 character long password generator as simply as possible, what i have so far is:

    import Foundation


    let chars = ["a","b","c","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u"        ,"v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"]

Thank you!

    var generate: String

    for generate in chars {
        print(generate)
    }
RufusV
  • 408
  • 3
  • 17

1 Answers1

0

As simply as possible use a loop and and a random number to get the character at given index:

let length = 8
var pass = ""
for _ in 0..<length {
  let random = arc4random_uniform(UInt32(chars.count))
  pass += chars[Int(random)]
}

print(pass)
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Would there be a way that you know of to iterate through all the possible passwords in order? I just want to make sure the same password is never generated twice. Thank you for the help though! – RufusV Jul 04 '16 at 15:22
  • 2
    @RufusV: Do you know how many passwords can be created from 8 alphanumeric characters? The answer is 218340105584896, and even if you create 10.000 per second then iterating over all will require many years ... – Martin R Jul 04 '16 at 15:24
  • For that purpose I recommend to use a hash function – vadian Jul 04 '16 at 15:24