Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 5. 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(...) instead [duplicate]

Tags:

swift

I have the method which has to print the username when the user connected but the error withUnsafeBytes is deprecated: use withUnsafeBytes(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R instead pops up.

method:

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

Somebody know how to solve it?

like image 927
Stanislav Marynych Avatar asked Apr 02 '19 22:04

Stanislav Marynych


2 Answers

It looks like withUnsafeBytes relies on assumingMemoryBound(to:) on Swift 5, there are some threads regarding it, e.g: https://forums.swift.org/t/how-to-use-data-withunsafebytes-in-a-well-defined-manner/12811

To silence that error, you could:

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)
    }
}

But it seems unsafe and confusing. It would be better to go with @OOper solution I think.

like image 147
backslash-f Avatar answered Nov 10 '22 13:11

backslash-f


You may find some solutions on how to use new Data.withUnsafeBytes, but if you are using it just for calling OutputStream.write, you have another option:

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

This code does not have a feature that crashes your app when username contains non-ascii characters, but other than that, it would work.

like image 44
OOPer Avatar answered Nov 10 '22 13:11

OOPer