gpt4 book ai didi

arrays - 检查非可选字符串数组在特定索引 Swift 处是否为空。不使用计数功能

转载 作者:搜寻专家 更新时间:2023-11-01 06:15:54 25 4
gpt4 key购买 nike

我有一个字符串数组,我想检查索引处的数组是否为空,然后我必须插入元素,如果它不为空,我必须更改该元素的值。我试过这个:

    var AnsArray = [String]()
let a_id = "Hello"
if (AnsArray[Indexpath.row].isEmpty){
AnsArray.insert(a_id, at: Indexpath.row)
}
else {
AnsArray[Indexpath.row] = a_id
}

但是报错:

fatal error: Index out of range

我也试过这个:

if (AnsArray[Indexpath.row] == "" ) {
AnsArray.insert(a_id, at: Indexpath.row)
}
else {
AnsArray[Indexpath.row] = a_id
}

它也给出了同样的错误。

Note: I can not use array.count because array can hold elements in specific index for example at index = 0 it can be empty and at index = 2 it can be stored some data.

最佳答案

您似乎想访问数组范围之外的项目。您的数组为空,因此调用 AnsArray[whateverIndexPath] 将始终导致此错误。

重要的是 Array 不能保存 nil 值——如果你的数组是空的,你不能像你描述的那样“检查特定索引”到。

此外,您不能在空数组中插入项 - 您插入的索引在插入之前必须已经有效。

因此,如果您想向数组中插入内容,您需要从头开始,使用append。或者,或者,用空字符串预填充您的数组。

AnsArray = [String](repeating: "", count: yourDesiredArrayCount)

if (AnsArray[Indexpath.row].isEmpty){
AnsArray[Indexpath.row] = "newValue"
}

关于arrays - 检查非可选字符串数组在特定索引 Swift 处是否为空。不使用计数功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45159586/

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