2016-07-04 79 views
0

我在我的第一應用的一個過程,它的目的是作爲一個密碼生成器,並告訴人們在1-1000規模有多難猜測,並有多難基於字母如何格式化,它看起來像什麼以及大腦如何記憶模式。到目前爲止,我有所有我想要在一個陣列中使用的字符,然後我有一個在循環,通過人物迭代,但我無法弄清楚如何指定密碼生成的長度,因爲目前它只是打印每個字符。於是,我問我怎樣才能使一個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) 
    } 

回答

0

儘可能簡單地用一個循環,並和隨機數在給定的索引來獲取字符:

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

print(pass) 
+0

會不會有你知道的方式,通過所有可能的密碼進行迭代訂購?我只是想確保相同的密碼永遠不會生成兩次。儘管謝謝您的幫助! – RufusV

+2

@RufusV:你知道可以用8個字母數字字符創建多少個密碼嗎?答案是218340105584896,即使你創造10.000每秒然後再遍歷所有這些都需要多年... –

+0

爲了這個目的,我建議使用散列函數 – vadian