使用'withUnsafeBufferPointer'从网络套接字读取Swift 3 - 'init'不可用'withMemoryRebound'

时间:2016-10-10 18:39:39

标签: xcode sockets swift3

我在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后,我遇到了这个错误。我无法弄清楚究竟需要改变什么,任何帮助都会非常感激

enter image description here

1 个答案:

答案 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。