Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array with capacity in Swift

Tags:

swift

How to initialise an array with maximum capacity without RepeatedValues?

var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)

Like in this example with repeatedValue. Can we initialise without a value?

like image 823
Mohit Jethwa Avatar asked Jun 26 '14 10:06

Mohit Jethwa


People also ask

What is array capacity in Swift?

The capacity property returns the total number of elements present in the array without allocating any additional storage.

How do I get the size of an array in Swift?

Swift – Array Size To get the size of an array in Swift, use count function on the array. Following is a quick example to get the count of elements present in the array. array_name is the array variable name. count returns an integer value for the size of this array.

Are arrays in Swift dynamic?

Swift arrays come in two flavors: dynamic and static.


3 Answers

CMD-clicking the Array type in Xcode finds me the following function definition (along with the doc comment):

/// Ensure the array has enough mutable contiguous storage to store /// minimumCapacity elements in.  Note: does not affect count. /// Complexity: O(N) mutating func reserveCapacity(minimumCapacity: Int) 

So in a way, you can tell an Array to pre-allocate storage for the given capacity by doing something like this:

var results: [T] = [] results.reserveCapacity(100) 

And theoretically, hundred appends on the array should then performs better than without the capacity reservation call.


To enforce "maximum" capacity though, there is no way to do that short of a custom code manually putting nils into an array of Optional<T>s capped to the maximum size as suggested by @Bryan in the question comments.

like image 188
chakrit Avatar answered Sep 20 '22 20:09

chakrit


UPDATE: As @chakrit says, you can use reserveCapacity now. This was added in later betas and is now available in the release version of Swift.

Arrays in Swift work differently than they do in Objective-C. In Swift you can't create an Array that has pre-allocated memory but does not contain elements. Just create an Array() and add as many elements as you want (3 in your case).

If you absolutely must do it this way, then use NSMutableArray like this:

var anotherThreeDoubles = NSMutableArray(capacity: 3) 

I hope I understood the question correctly. Feel free to explain further.

like image 41
Jernej Strasner Avatar answered Sep 20 '22 20:09

Jernej Strasner


For Swift 3.0, Value must be an optional type

    var arrImages = [UIImage?](repeating: nil, count: 64)
like image 39
Hiren Panchal Avatar answered Sep 19 '22 20:09

Hiren Panchal