Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/99.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

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
关于swift中的数组(ios)_Ios_Swift_Xcode_Swift4 - Fatal编程技术网

关于swift中的数组(ios)

关于swift中的数组(ios),ios,swift,xcode,swift4,Ios,Swift,Xcode,Swift4,如何设置数组的大小?在C++中,类似 int *P.DARR=新的int(num)< /代码>。我有一个类数组,我想在中为我的类设置数据。但是我不知道如何设置数组的大小.append帮不了我。我需要对象的动态数组。您可以在swift中使用此数组初始值设定项: var array = [Int](repeating: 0, count: num) 这将创建一个零为numcount的数组。然后可以通过for循环中的索引访问数组元素,如下所示: for index in 0..<array.c

如何设置数组的大小?在C++中,类似<代码> int *P.DARR=新的int(num)< /代码>。我有一个类数组,我想在
中为我的类设置数据。但是我不知道如何设置数组的大小
.append
帮不了我。我需要对象的动态数组。

您可以在swift中使用此数组初始值设定项:

var array = [Int](repeating: 0, count: num)
这将创建一个零为
num
count的数组。然后可以通过for循环中的索引访问数组元素,如下所示:

for index in 0..<array.count {
    // Set here your new value
    let newValue = ...
    array[index] = newValue 
}

Swift数组中0中索引的
动态调整大小。您不必将阵列预先分配到给定的大小。您可以使用如下代码:

class Foo {
   //foo properties
}
let arraySize = 1000
var array: [Foo] = []
for _ in 1... arraySize {
   let aFoo = Foo()
   //configure aFoo
   array.append(aFoo)
}
变量数组使用指数分配策略,为额外元素分配空间非常有效。(每次阵列超过其先前的大小时,其使用的空间量都会翻倍。)如果您知道阵列的大小,可以使用阵列
reserveCapacity()
函数为阵列预先分配空间:

class Foo {
   //foo properties
}
let arraySize = 1000
var array: [Foo] = []

array.reserveCapacity(arraySize) //This is the extra line

for _ in 1... arraySize {
   let aFoo = Foo()
   //configure aFoo
   array.append(aFoo)
}

如果我有一个类,您还可以使用@silicon\u valley

提到的数组
init(重复:count:)
初始值设定项?我的类需要一个替换int?在
repeating
中,我是否也指定了我的类?我试过了,但是所有数组中的数据都是相等的。您也可以使用自定义类的数组。在
重复之后插入的值是将为数组中的所有项设置的值。如果希望有不同的值,可以在数组上循环时设置这些值