我正在为iOS构建一个随机密码生成器。在其中,一个按钮生成一个随机密码,该密码具有用户选择的特征(例如,用于打开或关闭小写和大写字母,字符和符号等的开关)。
用户界面看起来很棒,其余的代码工作正常,但我无法让我的按钮实际生成一个随机的字母数字字符串。我有一个带有一些占位符文本(“你的密码”)的标签,按下按钮时应该将其文本更新为随机字符串,但是我收到编译错误:“未解析使用标识符'长度'”
以下是该按钮的当前代码:
@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"
}
谢谢!
答案 0 :(得分:10)
首先创建一个包含密码允许字符的数组
let passwordCharacters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".characters)
然后选择密码lenght
let len = 8
定义并清空字符串密码
var password = ""
创建一个循环来生成随机字符
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
您也可以使用map而不是标准循环:
let pswdChars = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
let rndPswd = String((0..<len).map{ _ in pswdChars[Int(arc4random_uniform(UInt32(pswdChars.count)))]})
print(rndPswd) // "oLS1w3bK\n"
Swift 4.2
使用新的Collection randomElement()
方法:
let len = 8
let pswdChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
let rndPswd = String((0..<len).compactMap{ _ in pswdChars.randomElement() })
print(rndPswd) // "3NRQHoiA\n"
答案 1 :(得分:1)
您的代码应为
...
for _ in 0 ..< len {
...
答案 2 :(得分:0)
您也可以使用
import Security
let password = SecCreateSharedWebCredentialPassword() as String?
print(password)