You could also capture a copy of data
or its count
in the closure's capture list:
data.withUnsafeMutableBytes {[data] ptr in
ptr[0] = UInt8(data.count)
}
data.withUnsafeMutableBytes {[count = data.count] ptr in
ptr[0] = UInt8(count)
}
The capture list gets evaluated and the results captured by value when the closure is formed, before the exclusive access begins, avoiding the overlapping access.