简体   繁体   English

关于Swift中的数组(iOS)

[英]About array in swift (ios)

how do I can set the size of an array? 如何设置数组的大小? like int *p_darr = new int[num] in c++. int *p_darr = new int[num] c ++中的int *p_darr = new int[num] I have a array of class and i want set data for my class in for . 我有一个班级数组,我想在forfor班级设置数据。 but i dont know how to set a size my array. 但是我不知道如何设置数组的大小。 .append not help me. .append对我没有帮助。 I need a dynamic array of object. 我需要一个动态对象数组。

In Swift arrays are dynamically sized. 在Swift中,数组是动态调整大小的。 You don't have to pre-allocate your array to a given size. 您不必将数组预先分配为给定的大小。 You can use code like this: 您可以使用如下代码:

class Foo {
   //foo properties
}
let arraySize = 1000
var array: [Foo] = []
for _ in 1... arraySize {
   let aFoo = Foo()
   //configure aFoo
   array.append(aFoo)
}

Variable Arrays use an exponential allocation strategy where allocating space for extra elements is quite efficient. 可变数组使用指数分配策略,其中为多余元素分配空间非常有效。 (Each time the array exceeds its previous size it doubles the amount of space used.) If you know how big your array is going to be, you can use the Array reserveCapacity() function to pre-allocate space for your array: (每次数组超过其先前的大小时,它将使使用的空间增加一倍。)如果您知道数组的大小,则可以使用Array 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)
}

You could also use the array init(repeating:count:) initializer as mentioned by @silicon_valley 您还可以使用@silicon_valley提到的数组init(repeating:count:)初始化程序

You could use this array initializer in swift: 您可以快速使用此数组初始化器:

var array = [Int](repeating: 0, count: num)

This will create an array with zeros of num count. 这将创建一个num为零的数组。 You can then access the elements of the array by index in a for loop like so: 然后,您可以在for循环中按索引访问数组的元素,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM