Array should have init(capacity: Int)

Instead of having to do this:


var array = [T]()
array.reserveCapacity(64)


You should be able to do this:


var array = [T](capacity: 64)


Which also makes this possible:


struct Foo {
   var data = [UInt8](capacity: 64)
    ...
}


Would be nice if String had this as well.

Replies

I agree this is a frequent use case which should justify an inclusion of this additional constructor in the standard library. In practice though, you can easily add this feature to `Array`:


extension Array {
  public init(capacity: Int) {
    self.init()
    self.reserveCapacity(capacity)
  }
}


This turns lines, like the following, into valid code:


var data = [UInt8](capacity: 64)

You can (sorta) already do that:

var foo = Foo()
var bar = [Foo](count:Int, repeatedValue:foo)


I suspect they're trying to avoid the problem of having an initialized array whose elements are not themselves initialized.


You could use protocols and extensions to do something like this:

protocol Initable {
     init()
}
extension Array where Element: Initable {
    init(count:Int) {
        self.init(count:count, repeatedValue:Element())
    }
}

Reserving capacity is different from initialising an array of a given size. An initialised array with a reserved capacity of n has zero length, but (hopefully) shouldn't have to have its underlying storage reallocated until more than n items are added to it.