Swift迭代字符长度

时间:2016-07-04 15:09:49

标签: ios swift string iteration

我正在制作我的第一个应用程序之一,它的目的是作为密码生成器,并告诉人们1-1000的规模猜测有多难,以及基于记忆的难度关于如何格式化字母以及它们的外观以及大脑如何记住模式。到目前为止,我有我想在数组中使用的所有字符,然后我有一个for循环遍历字符,但我无法弄清楚如何指定要生成的密码的长度,因为它目前只打印每个角色。所以,我问我怎样才能尽可能简单地制作一个8字符长的密码生成器,到目前为止我是:

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

谢谢!

    var generate: String

    for generate in chars {
        print(generate)
    }

1 个答案:

答案 0 :(得分:0)

尽可能简单地使用循环和随机数来获取给定索引处的字符:

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

print(pass)