I’m trying to use MutableSpan in a project for the first time. I’m having difficulty with a couple things:
-
Is it intentional that there’s no
UnsafeMutableRawBufferPointer.mutableSpan? I expected such a property to exist and return aMutableRawSpan. As a workaround, I am usingUnsafeMutableBufferPointer<UInt8>for my read buffers, and passing aroundMutableSpan<UInt8>s. -
When I try to pass a borrowed
MutableRawSpanto a function, I cannot assign to it:
let buf = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: 1)
doStuff(with: buf.mutableSpan)
func doStuff(with span: borrowing MutableSpan<UInt8>) {
span[0] = 42
// error: cannot assign through subscript: 'span' is a 'let' constant
}
…but if I make MutableSpan an inout, the error moves to the call site:
let buf = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: 1)
doStuff(with: &buf.mutableSpan)
// cannot pass immutable value as inout argument: 'mutableSpan' is a get-only property
func doStuff(with span: inout MutableSpan<UInt8>) {
span[0] = 42
}
I can’t even work around this by using the .mutableBytes property, because it is declared mutating get:
let buf = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: 1)
doStuff(with: buf.mutableSpan)
func doStuff(with span: borrowing MutableSpan<UInt8>) {
span.mutableBytes.storeBytes(of: 42, as: UInt8.self)
// error: cannot use mutating getter on immutable value: 'span' is a 'let' constant
// error: cannot use mutating member on immutable value: 'mutableBytes' is a get-only property
}
What is the correct pattern here? I’m on Swift 6.2.3.