I am using this to remove the background of an image in swift. It works fine in Debug build configuration and crashes in the release build configuration
func chromaKeyFilter(fromHue: CGFloat, toHue: CGFloat) -> CIFilter? {
// 1
let size = 64
var cubeRGB = [Float]()
// 2
for z in 0 ..< size {
let blue = CGFloat(z) / CGFloat(size-1)
for y in 0 ..< size {
let green = CGFloat(y) / CGFloat(size-1)
for x in 0 ..< size {
let red = CGFloat(x) / CGFloat(size-1)
// 3
let hue = getHue(red: red, green: green, blue: blue)
let alpha: CGFloat = (hue >= fromHue && hue <= toHue) ? 0: 1
// 4
cubeRGB.append(Float(red * alpha))
cubeRGB.append(Float(green * alpha))
cubeRGB.append(Float(blue * alpha))
cubeRGB.append(Float(alpha))
}
}
}
let data = Data(buffer: UnsafeBufferPointer(start: &cubeRGB, count: cubeRGB.count))
// 5
let colorCubeFilter = CIFilter(name: "CIColorCube", parameters: ["inputCubeDimension": size, "inputCubeData": data])
return colorCubeFilter
}
the error is Thread 1: EXC_BAD_ACCESS (code=1, address=0x15f700020)
.
I do see the warning : Initialization of 'UnsafeBufferPointer<Float>' results in a dangling buffer pointer
I am guessing swift compiler optimations cause the crash but I don't how to solve this.
EDIT: I manage to avoid the crash by changing the Swift Compiler - Optimization Level to No Optimization [-Onone] but I guess it is not ideal