【问题标题】:How to get rid of warning using withUnsafeBytes() and outputStream.write() in Swift 5.0如何在 Swift 5.0 中使用 withUnsafeBytes() 和 outputStream.write() 消除警告
【发布时间】:2019-05-05 00:22:20
【问题描述】:

我有以下功能,我无法摆脱编译警告。 警告 = '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> 不受支持?不确定??

【问题讨论】:

    标签: swift deprecated outputstream


    【解决方案1】:

    这将在 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)
    

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多