Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java到Swift的转换-如何在Swift中增加索引计数_Java_Swift - Fatal编程技术网

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

Java到Swift的转换-如何在Swift中增加索引计数,java,swift,Java,Swift,这看起来很简单,但我被卡住了。我得到的是通常的索引超出范围的快速错误。似乎Java可以从一开始就设置数组的索引数量,并增加索引总数 我知道问题是什么,但我不知道这个Java函数的Swift等价物。Java函数有一个post incrementor,用于增加空数组的索引计数。我不知道怎么用Swift写。使用Swift时,必须使用append。不能在空数组上使用订阅。另外,我不知道如何增加索引计数 如何将此Java转换为Swift 爪哇 迅捷的 根据文档,要使用默认大小初始化数组,请使用 var t

这看起来很简单,但我被卡住了。我得到的是通常的索引超出范围的快速错误。似乎Java可以从一开始就设置数组的索引数量,并增加索引总数

我知道问题是什么,但我不知道这个Java函数的Swift等价物。Java函数有一个post incrementor,用于增加空数组的索引计数。我不知道怎么用Swift写。使用Swift时,必须使用append。不能在空数组上使用订阅。另外,我不知道如何增加索引计数

如何将此Java转换为Swift

爪哇

迅捷的


根据文档,要使用默认大小初始化
数组
,请使用

var theArray = Array(repeating: "", count: itemsInArray) // Where repeating is the contained type 
然后,您可以通过

theArray.insert(newItem, at: yourIndex)
Java中的
数组必须具有初始
大小,创建后不能更改。但是,Swift的类型与Java
Collection
类型相当,后者可以具有变量
size

比如说

private int[] theArray;
将编译,但在第一次访问时也会生成
NullPointerException
,因为它没有正确初始化

private int[] theArray = { 1, 2, 3, 4 };
private int[] theArray = new int[10];
在Java和Swing中,使用Java中的
myArray[index]
表示法或Swing中的
myArray.insert(item,at:index)
表示法访问正确的索引范围也需要小心


示例中的Java行
数组[itemsInArray++]=newItem
表示

  • newItem
    值分配给
    itemsInArray
    索引
  • 增量
    itemsInArray
    (参见增量后运算符)
  • 在Swift中,您只需将新元素附加到
    数组
    ,甚至不需要维护类似
    itemsInArray

    var theArray = ["One", "Two", "Three"]
    theArray.append("Four")
    
    var theIntegerArray = [1, 2, 3]
    theIntegerArray.append(4)
    
    或者使用空数组

    var theIntegerArray: Array<Int> = []
    theIntegerArray.append(4)
    

    但使用Swift时,您必须使用append–这是否已经回答了您的问题?是否有任何理由使用
    itemsInArray
    ?您可以只使用
    theArray.append(newItem)
    ,然后只需使用
    theArray.count
    即可获得可用元素的数量。Swift数组更像是一个
    列表
    ,而Java数组“Java可以设置一个数组从一开始就拥有的索引数量,并增加索引总数”——不确定这是否有意义。Java数组是固定长度的,代码所做的是将索引移动到下一个位置,然后将值应用到该元素,但由于它没有防止
    itemsInArray
    可能高于可用元素的事实(即
    length
    )它还可以生成一个
    IndexOutOfBoundsException
    ,而Swift代码甚至还没有达到同样的效果thing@TokyoToo我在答案中添加了一些解释。@Tokyoo参见更新的答案。问问你是否需要clarifications@TokyoToo那么我的答案的前四行就足够了。只需创建一个具有默认初始大小的新数组,然后使用insert。这将是最类似的版本Java@TokyoToo是的,这里您从一个空数组开始,但是您没有维护索引。这是我在回答中使用的同一个例子,与Java的例子不可比。@Tokyoo也看到了“或带有空数组”部分。
    var theArray = ["One", "Two", "Three"]
    theArray.append("Four")
    
    var theIntegerArray = [1, 2, 3]
    theIntegerArray.append(4)
    
    var theIntegerArray: Array<Int> = []
    theIntegerArray.append(4)
    
    Array(repeating: 0, count: itemsInArray)