Java 到 Swift 的转换 - 如何在 Swift 中增加索引计数

这看起来很简单,但我被卡住了。我得到了通常的 Index Out Of Bounds Swift 错误。似乎Java可以从一开始就设置数组的索引数量,也可以增加索引的总数。


我知道问题出在哪里,但我不知道这个 Java 函数的 Swift 等价物。Java 函数有一个后置增量器,用于增加 EMPTY 数组的索引计数。我不知道如何在 Swift 中编写它。使用 Swift 你必须使用 append。您不能在空数组上使用下标。加上我不知道如何增加索引计数。


如何将此 Java 转换为 Swift?


爪哇


private int[] theArray;

private int itemsInArray = 0;


public void addItemToArray(int newItem) {

        theArray[itemsInArray++] = newItem;

    }

迅速


var theArray = [Int]()

var itemsInArray = 0


func addItemArray(newItem: Int) {

    theArray[itemsInArray] += newItem

}

addItemArray(newItem: 5)


SMILET
浏览 118回答 1
1回答

潇潇雨雨

Array根据文档,使用默认大小初始化var theArray = Array(repeating: "", count: itemsInArray) // Where repeating is the contained type&nbsp;然后你可以insert通过theArray.insert(newItem, at: yourIndex)Array(s) 在 Java 中必须有一个首字母size,创建后不能更改。然而 Swift 有与 Java 类型相当的Collection<T>类型,Java 类型可以有 variable size。例如private int[] theArray;将编译,但它也会NullPointerException在第一次访问时产生 a,因为它没有正确初始化private int[] theArray = { 1, 2, 3, 4 };private int[] theArray = new int[10];在 Java 和 Swing 中,您还需要小心使用myArray[index]Java 中的表示法或myArray.insert(item, at: index)Swing 中的表示法访问正确的索引范围。您的示例的 Java 行theArray[itemsInArray++] = newItem意味着将newItem值分配给itemsInArray索引增量itemsInArray(参见后增量运算符)在 Swift 中,您只需将一个新元素附加到Array,您甚至不需要维护一个索引itemsInArrayvar theArray = ["One", "Two", "Three"]theArray.append("Four")var theIntegerArray = [1, 2, 3]theIntegerArray.append(4)或使用空数组var theIntegerArray: Array<Int> = []theIntegerArray.append(4)是的,您可以使用repeatingwithInteger值。只是Array(repeating: 0, count: itemsInArray)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java