gpt4 book ai didi

arrays - Swift 数组 - "Int.random(in: 0...25)"和 "randomElement()"之间的差异

转载 作者:行者123 更新时间:2023-12-02 03:35:48 24 4
gpt4 key购买 nike

我最近开始通过在线类(class)学习 swift。

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

  1. 变量[Int.random(in: 0...25)]
  2. 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 是这里使用的更好的方法,因为它迫使您考虑数组为空的情况,并相应地进行处理。第一种使用下标的方法不检查数组是否为空,或者索引是否正确等。

关于arrays - Swift 数组 - "Int.random(in: 0...25)"和 "randomElement()"之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com