我最近开始通过在线课程学习Swift。

我得到了从包含字符的给定数组中生成密码的任务。
我们主要学习了两个代码示例以随机选择一个。


variable[Int.random(in: 0...25)]
variable.randomElement()


当从数组中拉出一个单个元素时,两者都工作得很好,但是当使用加号(+)多次组合时,只能使用“ variable[Int.random(in: 0...25)”。

这是为什么?



我查阅了文档,但找不到答案

https://developer.apple.com/documentation/swift/array/2994747-randomelement



说明:

此代码有效:

let alphabet = ["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"]

//The number of letters in alphabet equals 26
var password = alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)]

print(password)


这段代码无法正常工作,因为“ randomElement()”在加倍数后会变灰(为什么?)

let alphabet = ["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"]

//The number of letters in alphabet equals 26
var password = alphabet.randomElement() + alphabet.randomElement() + alphabet.randomElement() + alphabet.randomElement() + alphabet.randomElement() + alphabet.randomElement()

print(password)


编辑:
谢谢你们的快速解释!

最佳答案

区别在于randomElement返回可选字符串(String?),而下标则返回非可选字符串。为什么randomElement返回可选字符串?好吧,如果数组为空怎么办?

而且Swift无法弄清楚如何添加2个可选字符串(更不用说6个了!所以它只是放弃了)。解决此问题的一种方法是强制展开randomElement的返回值:

let password = alphabet.randomElement() + alphabet.randomElement() + alphabet.randomElement()! + alphabet.randomElement()! + alphabet.randomElement()! + alphabet.randomElement()!


我们知道数组不是空的,因此我们可以在此处安全地强制展开。

可以说,randomElement是在此处使用的更好的方法,因为它迫使您考虑数组为空的情况,并相应地进行处理。第一种使用下标的方法不检查数组是否为空,或者索引是否正确等。

10-08 13:31