如何在Swift 5.0中使用withUnsafeBytes()和outputStream.write()摆脱警告

时间:2019-05-05 00:22:20

标签: swift deprecated outputstream

我在下面具有以下功能,并且无法摆脱编译警告。 警告='withUnsafeBytes'已过时:改为使用withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R

我尝试了有关withUnsafeBytes(包括stackoverflow.com)的在线文档,但是withUnsafeBytes()的糟糕文档与异常函数outputStream.write(需要UnsafePointer)混合在一起使我无法理解必须如何传递指针,也无法理解$ 0指的是什么。我知道$ 0是代码闭包的隐式参数,但是我得到的代码没有明确列出闭包参数,因此我无法弄清楚什么是$ 0。

func sendMessage(message: String)
{
    // URL Encode the message
    let URLEncodedMem = UnsafeMutablePointer<UInt8>.allocate(capacity: message.utf8CString.count * 3 + 1)
    defer { URLEncodedMem.deallocate() }
    urlEncode( URLEncodedMem, message )
    let urlEncodedMsg = String( cString: URLEncodedMem )

    // Build the server message to send
    let strToSend = "GET /userInput.mtml?userInput=\(urlEncodedMsg) HTTP/1.1\r\n"
            +       "Host: \(hostName):\(hostPort)\r\n\r\n"
    let data = strToSend.data(using: .utf8)!

    _ = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }  // Warning = 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
}   //  sendMessage

即使SWIFT使用withUnsafeBytes进行其他更改,我也希望代码能够继续工作。

我怀疑问题可能在于不支持withUsafeBytes>?不确定?

1 个答案:

答案 0 :(得分:0)

这将在Swift 5中正确编译。

let strToSend = "GET /userInput.mtml?userInput=\(urlEncodedMsg) HTTP/1.1\r\n"
    +       "Host: \(hostName):\(hostPort)\r\n\r\n"
let data = strToSend.data(using: .utf8)!

_ = data.withUnsafeBytes { outputStream.write($0.bindMemory(to: UInt8.self).baseAddress!, maxLength: data.count) }

(您可以在SO中找到有关弃用旧withUnsafeBytes的文章。)

但是在您的情况下,您可以简单地将其写为:

let strToSend = "GET /userInput.mtml?userInput=\(urlEncodedMsg) HTTP/1.1\r\n"
    +       "Host: \(hostName):\(hostPort)\r\n\r\n"

outputStream.write(strToSend, maxLength: strToSend.utf8.count)