Swift init Array with capacity

后端 未结 5 1196
执念已碎
执念已碎 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(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(count: 16, repeatedValue: nil);
    

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

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

    or

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

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

提交回复
热议问题