I working on a Mac App where I'm using an Array or ContiguousArray to provide memory for a Bitmap. I have a struct that emulates the bitmap pixel
public struct PixelColor {
public var r, g, b, a: UInt8
public init(r: UInt8, g: UInt8, b: UInt8, a: UInt8 = 255) {
self.r = r
self.g = g
self.b = b
self.a = a
}
}
public extension PixelColor {
static let clear = PixelColor(r: 0, g: 0, b: 0, a: 0)
static let black = PixelColor(r: 0, g: 0, b: 0)
static let white = PixelColor(r: 255, g: 255, b: 255)
static let red = PixelColor(r: 217, g: 87, b: 99)
static let green = PixelColor(r: 153, g: 229, b: 80)
static let yellow = PixelColor(r: 251, g: 242, b: 54)
}
If I initialize it as
Array(repeating: .black, count: WaterfallSettings.columns * WaterfallSettings.rows)
It works as expected, but if I switch it to a ContigousArray, I get a EXC_BAD_ACCESS error. Also, if instead I create it as a two-dimensional array:
Array(repeating: Array(repeating: .black, count: WaterfallSettings.columns), count: WaterfallSettings.rows)
I get similar EXC_BAD_ACCESS error
I think the problem is that the ContiguousArray(repeating: count:) or the Array(repeating: Array(repeating: count:), count:) are initializing the arrays, but using one instance of the .black struct or the array and pointing the other references to it. Once you actually update an element CopyOnWrite cleans things up, but messes up the pointer that my Bitmap is using.
Is there a way to force Array(repeating: count:) to allocate space for all the elements and make separate copies?
TIA,
Mark