arrays - 无法使用 index++ 在 Swift 中追加数组

标签 arrays swift

我正在尝试编写一些代码,将我的数组附加到此: ["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/

相关文章:

javascript - 数组中不允许有重复元素?错误: ngRepeat:dupes

Swift 用户创建未检测 UIText 长度

swift - 使用多行 Swift 字符串构建多部分表单数据不起作用

ios - 如果点击后退按钮,导航栏标题颜色不会改变

ios - 无法初始化 PFObject 子类

android - 使用带有 Retrofit 和 Kotlin 的 moshi 将 jsonarray 解析为对象

c - 中止陷阱 : 6, 使用 memcpy 复制数组

arrays - Delphi中如何合并2个字符串数组

c - 如何动态地将字符串插入到 C 结构内部的二维数组中?

ios - 升级到 Xcode 7.1 - "Google Mobile Ads"找不到框架