Reputation: 633
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?
Upvotes: 21
Views: 28817
Reputation: 1365
Even though there's a reserveCapacity
function, it's not advised
from the docs:
The Array type’s append(:) and append(contentsOf:) methods take care of this detail for you, but reserveCapacity(:) allocates only as much space as you tell it to (padded to a round value), and no more. This avoids over-allocation, but can result in insertion not having amortized constant-time performance.
Apple says it's better to let the array's append
and append(contentsOf:)
functions to take care of this for you unless you know the capacity of the array without calling the count
property on a collection. They also have an example on the page I linked above.
Upvotes: 1
Reputation: 3023
For Swift 3.0, Value must be an optional type
var arrImages = [UIImage?](repeating: nil, count: 64)
Upvotes: 6
Reputation: 4620
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.
Upvotes: 6
Reputation: 61518
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 append
s 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 nil
s into an array of Optional<T>
s capped to the maximum size as suggested by @Bryan in the question comments.
Upvotes: 25
Reputation: 64644
As Jernej said, you can use NSMutableArray
in this case. Note that both NSMutableArray and Swift Arrays do not actually limit how many elements you can add:
var anotherThreeDoubles = Array(count: 3, repeatedValue:10)
anotherThreeDoubles += 10 //another 3 doubles now has 4 elements
var arr: Array = NSMutableArray(capacity: 3)
arr.append(10)
arr.append(10)
arr.append(10)
arr.append(10) //arr now has 4 elements
Upvotes: 1