Search code examples
swiftpointersallocation

Memset to UnsafeMutablePointer<UInt8> in swift


I have a challenge with a variable with type UnsafeMutablePointer<UInt8>.

I have this working code to alloc and set to zero all an UInt8 array in Swift.
var bits = UnsafeMutablePointer<UInt8>(calloc(width * height, 8))

The problem is I'd like to do it without use the calloc method. I have this code to alloc the array
var bits = UnsafeMutablePointer<UInt8>.alloc(width * height)

but I can't find a method to set to zero all the memory.

I know I can do this, but I don't think is the best way.

for index in 0..< (width * height) {
    bits[index] = 0
}

Solution

  • You could say:

    bits.initializeFrom(Array<UInt8>(count: width * height, repeatedValue: 0))
    

    I'm guessing there's some underlying efficiency to copying the memory this way. But of course there's an inefficiency in that we temporarily make the array. [NOTE: AirspeedVelocity's answer shows a way to avoid that.]

    Personally, I liked your original loop best, especially if you write it more compactly, like this:

    (0 ..< (width*height)).map {bits[$0] = 0}