我在Swift 2.3中有一个从网络套接字读取Int值的函数
open func readInt() -> Int32 {
var intValueBuffer = [UInt8](repeating: 0, count: MemoryLayout<Int32>.size)
self.stream!.read (&intValueBuffer, maxLength: MemoryLayout<Int32>.size)
let intValue = intValueBuffer.withUnsafeBufferPointer({
UnsafePointer<Int32>($0.baseAddress!).pointee
})
return Int32(bigEndian: intValue)
}
迁移到Swift 3之后,我遇到了这个错误。我还无法弄清楚实际需要更改的内容,我们将不胜感激
最佳答案
从UInt8
指针到Int32
指针的转换
必须使用withMemoryRebound()
明确指定:
func readInt() -> Int32 {
var intValueBuffer = [UInt8](repeating: 0, count: MemoryLayout<Int32>.size)
self.stream!.read(&intValueBuffer, maxLength: MemoryLayout<Int32>.size)
let intValue = intValueBuffer.withUnsafeBufferPointer({
$0.baseAddress!.withMemoryRebound(to: Int32.self, capacity: 1) {
$0.pointee
}
})
return Int32(bigEndian: intValue)
}
或者,读入
Data
对象而不是数组:func readInt() -> Int32 {
var intValueBuffer = Data(count: MemoryLayout<Int32>.size)
intValueBuffer.withUnsafeMutableBytes {
_ = self.stream!.read($0, maxLength: MemoryLayout<Int32>.size)
}
return Int32(bigEndian: intValueBuffer.withUnsafeBytes { $0.pointee })
}
或直接转换为整数变量:
func readInt() -> Int32 {
var intValue: Int32 = 0
withUnsafePointer(to: &intValue) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<Int32>.size) {
_ = self.stream!.read($0, maxLength: MemoryLayout<Int32>.size)
}
}
return Int32(bigEndian: intValue)
}
有关更多信息,请参见swift.org上的UnsafeRawPointer Migration。
您可能还需要检查
read
方法的返回值这是实际读取的字节数;如果读取操作失败,则为-1。
关于xcode - Swift 3使用 'withUnsafeBufferPointer'从网络套接字读取- 'init'无法使用 'withMemoryRebound',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964712/