Swift 5.不推荐使用'withUnsafeBytes':改用`withUnsafeBytes <r>(...)

时间:2019-04-02 22:13:22

标签: swift

我有一种方法,必须在用户连接时打印用户名,但不建议使用错误 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
    }

有人知道如何解决吗?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

看起来withUnsafeBytes依赖于Swift 5上的assumingMemoryBound(to:),有一些关于它的线程,例如:https://forums.swift.org/t/how-to-use-data-withunsafebytes-in-a-well-defined-manner/12811

要使该错误消失,您可以:

func joinChat(username: String) {
    let data = "iam:\(username)".data(using: .ascii)!
    self.username = username
    _ = data.withUnsafeBytes { dataBytes in
        let buffer: UnsafePointer<UInt8> = dataBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
        OutputStream(toMemory: ()).write(buffer, maxLength: dataBytes.count)
    }
}

但这似乎不安全且令人困惑。我认为最好使用@OOper解决方案。