Reputation: 571
Trying to clean up some warnings in my SWIFT 5/XCODE project and I'm stuck on this one:
let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let msgData = Data(bytes: UnsafePointer<UInt8>(sendBytes), count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)
For the "UnsafePointer" I'm getting the following warning and two suggestions:
Initialization of 'UnsafePointer' results in a dangling pointer
Implicit argument conversion from '[UInt8]' to 'UnsafePointer' produces a pointer valid only for the duration of the call to 'init(_:)'
Use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope
This is my solution, better?
Version 1:
let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, count: sendBytes.count)
let msgData = Data(bytes: uint8Pointer, count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)
Version 2:
let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, count: sendBytes.count)
let msgData = Data(bytes: uint8Pointer, count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)
uint8Pointer.deallocate()
Upvotes: 2
Views: 2261
Reputation: 285260
Since Swift 3 it's possible to simply initialize a Data
instance with an UInt8
array.
let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let msgData = Data(sendBytes)
Upvotes: 7