Mav*_*vro 2 xcode swift swift5
试图清除我的 SWIFT 5/XCODE 项目中的一些警告,但我陷入了这一困境:
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)
Run Code Online (Sandbox Code Playgroud)
对于“UnsafePointer”,我收到以下警告和两条建议:
“UnsafePointer”的初始化导致悬空指针
从“[UInt8]”到“UnsafePointer”的隐式参数转换生成一个仅在调用“init(_:)”期间有效的指针
在数组上使用“withUnsafeBufferPointer”方法,以便将参数显式转换为对定义范围有效的缓冲区指针
这是我的解决方案,更好吗?
版本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)
Run Code Online (Sandbox Code Playgroud)
版本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()
Run Code Online (Sandbox Code Playgroud)
从 Swift 3 开始,可以简单地Data使用UInt8数组初始化实例。
let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let msgData = Data(sendBytes)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2106 次 |
| 最近记录: |