RufusV RufusV - 1 year ago 81
Swift Question

Swift Iteration Character Length

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 {

Answer Source

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)]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download