After update to Swift 5.2 / Xcode 11.4 got a warning to following code:
extension Data {
init<T>(from value: T) {
var value = value
let pointer = UnsafeBufferPointer(start: &value, count: 1)
self.init(buffer: pointer)
}
func to<T>(type: T.Type) -> T {
return self.withUnsafeBytes { $0.load(as: T.self) }
}
}
On line let pointer = UnsafeBufferPointer(start: &value, count: 1) I got
Initialization of 'UnsafeBufferPointer' results in a dangling buffer pointer
I can use @silenceWarning but it's dirty solution. Maybe I need to store pointer somewhere and clean it in the future?
This was never safe, so glad that the Swift team has cleaned it up:
At the end of this line of code,
pointer
is immediately invalid. There is not promise thatvalue
even exists at the next line of code. I'm not sure what you were trying to achieve here, but this was never a safe way to do it. What you're likely looking for is one of the.withUnsafeBytes
methods, which depends on what you were working on.