j.s.com
j.s.com

Reputation: 1458

memset with Swift 5.2

Sometimes I need to clear a part of a byte array to zero. With a for loop this is slow. Much faster is using the memset() function. I have the following code which will clear elements 200 to 299 of the array "a".

var a: [UInt8] = [UInt8](repeating: 1, count: 1000) // a[0..999] set to 1
start = 200
length = 100
memset(&a + start, 0, length) // a[100..199] set to 0

This worked well until Swift 5.2 with Xcode 11.4 came out. Now it works, too, but a warning appears:

Inout expression creates a temporary pointer, but argument #1 should be a pointer that outlives the call to '+'

How can this made, to have no warning.? Andybody has an idea?

Some more explanations is whows in Xcode:

  1. Implicit argument conversion from '[UInt8]' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to '+'

  2. Use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope

I do not understand, what this means.

Upvotes: 2

Views: 1604

Answers (1)

Gereon
Gereon

Reputation: 17844

The hint to use withUnsafeMutableBytes is exactly what you should follow:

a.withUnsafeMutableBytes { ptr in
    _ = memset(ptr.baseAddress! + start, 0, length)
}

Upvotes: 3

Related Questions