我在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后,我遇到了这个错误。我无法弄清楚究竟需要改变什么,任何帮助都会非常感激
答案 0 :(得分:2)
从指向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。