我正在尝试编写一些代码,将我的数组附加到此: ["e", "0", "", "0"] 但是我得到的是:["e", "0", "0"]。我不明白为什么它显示后者,因为据我所知,当我向它添加 2 时,索引变为 3。 此外,当我尝试运行此命令时,我还会收到“ fatal error :数组索引超出范围”:TheTape.insert("0", atIndex: index+2)。在这里我也不明白为什么我没有指定数组的大小时它会超出范围。
感谢您的帮助!
import UIKit
var TheTape = [Any]()
var index = 0
if(TheTape.isEmpty){
TheTape.insert("e", atIndex: 0)
print(TheTape)
index++
TheTape.insert("0", atIndex: index)
print(TheTape)
index + 2
TheTape.insert("0", atIndex: index)
print(TheTape)
}
最佳答案
基本上你是这样做的;
TheTape.insert("e", atIndex: 0) // array = ['e'] (insert at 0)
print(TheTape)
index++ // index 0 -> 1
TheTape.insert("0", atIndex: index) // array = ['e', '0'] (insert at 1)
print(TheTape)
index + 2 // Does nothing
TheTape.insert("0", atIndex: index) // array = ['e', '0', '0'] (insert at 1)
print(TheTape)
如您所见,如果您想增加索引为 2,使用 index += 2
。
在数组外的索引处插入是错误的,会给出您所看到的错误。如果您想要一个空值来分隔这些值,则需要先插入它。
关于arrays - 无法使用 index++ 在 Swift 中追加数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35300132/