Reputation: 3
how do I can set the size of an array? like int *p_darr = new int[num]
in c++. I have a array of class and i want set data for my class in for
. but i dont know how to set a size my array. .append
not help me. I need a dynamic array of object.
Upvotes: 0
Views: 256
Reputation: 131491
In Swift arrays are dynamically sized. 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:
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
Upvotes: 1
Reputation: 2689
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. You can then access the elements of the array by index in a for loop like so:
for index in 0..<array.count {
// Set here your new value
let newValue = ...
array[index] = newValue
}
Upvotes: 0