Refactoring withUnsafeMutableBytes

What is the correct way to re-write this code:

    randomIV = Data(count: 16)
		let result = randomIV.withUnsafeMutableBytes {
			SecRandomCopyBytes(kSecRandomDefault, 16, $0)
		}

To remove this warning:

'withUnsafeMutableBytes' is deprecated: use withUnsafeMutableBytes(_: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead

Answered by OOPer in 711242022

You can re-write it like this:

    let result = randomIV.withUnsafeMutableBytes {(bufPointer: UnsafeMutableRawBufferPointer) in
        SecRandomCopyBytes(kSecRandomDefault, bufPointer.count, bufPointer.baseAddress!)
    }

Or a little more simply:

    let result = randomIV.withUnsafeMutableBytes {
        SecRandomCopyBytes(kSecRandomDefault, $0.count, $0.baseAddress!)
    }
Accepted Answer

You can re-write it like this:

    let result = randomIV.withUnsafeMutableBytes {(bufPointer: UnsafeMutableRawBufferPointer) in
        SecRandomCopyBytes(kSecRandomDefault, bufPointer.count, bufPointer.baseAddress!)
    }

Or a little more simply:

    let result = randomIV.withUnsafeMutableBytes {
        SecRandomCopyBytes(kSecRandomDefault, $0.count, $0.baseAddress!)
    }
Refactoring withUnsafeMutableBytes
 
 
Q