More fun with sequences!

I want to share a little conversation from Swift-Users. KS Sreeram wrote:

I’m trying to initialize a byte-array efficiently with minimal copying with the following steps:

1. Create an empty byte array.
2. Reserve sufficient capacity in the array.
3. Use mutable pointers into the array to fill in the data.
4. The actual size that was filled is known only after it is filled in.
5. I would like to set the size of the array to the actual size.

I couldn’t find any methods for doing the last step. Is there a way to do this?

Dave Abrahams’ response:

Create a Sequence that represents the elements you’re going to append, e.g.:

 var a = [1, 2]
 a += sequence(first: 3, next: {$0 < 1000 ? ($0 + 3) * 2 : nil})

There are lots of ways to make Sequences, but the overloaded sequence() functions are probably the easiest.



  • I pasted the above code into a sandbox, nothing works, no methods are found: i.e. “reserve” and “sequence”

  • a.reserve(256) becomes a.reserveCapacity(256) in Swift 3

    • I’m using Swift 2.2 and Xcode 7.3.1 – I had to use reserveCapacity – maybe reserve is Swift 3? Also, cannot find “sequence” – tried it in a sandbox, then searched in Dash – no luck.