wcochran
wcochran

Reputation: 10896

Should I be using Swift ContiguousArray's to hold image data?

I am currently using a buffer of type [UInt8] to hold pixel data read from a CGImage as follows:

var pixels = [UInt8](repeatElement(0, count: bytesPerRow*Int(height)))
let context = CGContext.init(data: &pixels,
                             width: width,
                             height: height,
                             bitsPerComponent: 8,
                             bytesPerRow: bytesPerRow,
                             space: colorSpace,
                             bitmapInfo: bitmapInfo)
 context!.draw(cgImage, in: rect)

This code makes the general assumption that pixels is a contiguous array of bytes holding the image data and it seems to work fine. I have this uneasy feeling I should be using ContiguousArray's for this. Am I really living dangerously here and should be doing something else?

Aside: I miss plain C when I always knew what was going on. Sigh.

Upvotes: 1

Views: 366

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185691

The primary difference between ContiguousArray and Array is the latter uses a different storage when the element type is a class or @objc protocol (this is so it can easily bridge to Obj-C). If the element type is not a class, they both use the same storage internally and it doesn't matter which one you pick.

In your case, the element type is not a class, so [UInt8] will behave the same as ContiguousArray<UInt8>.

Upvotes: 2

Related Questions