This question already has answers here:
Swift 5.0: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(…)

(4个答案)


2年前关闭。




我有一种方法必须在用户连接时打印用户名,但不建议使用 withUnsafeBytes错误:使用withUnsafeBytes(_:(UnsafeRawBufferPointer)throws-> R)rethrows-> R而不是弹出

方法:
    func joinChat(username: String) {
      let data = "iam:\(username)".data(using: .ascii)!
      self.username = username
      _ = data.withUnsafeBytes { outputStream.write($0, maxLength:    data.count) } //deprecated
    }

有人知道如何解决吗?

最佳答案

您可能会找到一些有关如何使用新Data.withUnsafeBytes的解决方案,但是如果仅将其用于调用OutputStream.write,则还有另一种选择:

func joinChat(username: String) {
    let str = "iam:\(username)"
    self.username = username
    outputStream.write(str, maxLength: str.utf8.count)
}

username包含非ASCII字符时,此代码不具有使您的应用程序崩溃的功能,但除此之外,它仍然可以工作。

10-06 02:39