Swift init Array with capacity

后端 未结 5 1107
执念已碎
执念已碎 2021-02-02 06:55

How do I initialize an Array in swift with a specific capacity?

I\'ve tried:

var grid = Array  ()
grid.reserveCapacity(16)
<
相关标签:
5条回答
  • 2021-02-02 07:43

    How about:

    class Square {
    
    }
    
    var grid = Array<Square>(count: 16, repeatedValue: Square());
    

    Though this will call the constructor for each square.

    If you made the array have optional Square instances you could use:

    var grid2 = Array<Square?>(count: 16, repeatedValue: nil);
    

    EDIT: With Swift3 this initializer signature has changed to the following:

    var grid3 = Array<Square>(repeating: Square(), count: 16)
    

    or

    var grid4 = [Square](repeating: Square(), count: 16)
    

    Of course, both also work with Square? and nil.

    0 讨论(0)
  • 2021-02-02 07:48

    Try:

    var grid = Array<Square>(count: 16, repeatedValue: aSquare)
    
    0 讨论(0)
  • 2021-02-02 07:53

    WARNING:

    If you use the Array(repeating:count:) initializer, you will encounter odd and unexpected behavior when using common array methods such as append( which will immediately defeat the purpose of reserving capacity by adding the new value outside the created capacity instead of an earlier point in the array.

    BETTER PRACTICE:

    Swift arrays dynamically double to meet the storage needs of your array so you don't necessarily need to reserve capacity in most cases. However, there is a speed cost when you don't specify the size ahead of time as the system needs to find a new memory location with enough space and copy over each item one by one in O(N) speed every time it doubles. On average, reallocation tends towards big O(LogN) as the array size doubles.

    If you reserve capacity you can bring the reallocation process down from O(N) or O(NlogN) on average down to nothing if you can accurately anticipate the size of the array ahead of time. Here is the documentation.

    You can do so by calling reserveCapacity(:) on arrays.

    var myArray: [Double] = []
    myArray.reserveCapacity(10000)
    
    0 讨论(0)
  • 2021-02-02 07:57
    var actions:[AnyObject?] = [AnyObject?](count: 3, repeatedValue: nil)
    
    0 讨论(0)
  • 2021-02-02 08:01

    Swift 3 / Swift 4 / Swift 5

    var grid : [Square]?
    grid?.reserveCapacity(16)
    

    I believe it can be achieved in one line as well.

    0 讨论(0)
提交回复
热议问题