gpt4 book ai didi

swift - 如何在 Swift 5.0 中使用 withUnsafeBytes() 和 outputStream.write() 消除警告

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:08 26 4
gpt4 key购买 nike

我在下面有以下功能,我无法摆脱编译警告。警告 = '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 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)

关于swift - 如何在 Swift 5.0 中使用 withUnsafeBytes() 和 outputStream.write() 消除警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55987885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com