Swift 5.0: 'Withunsafebytes' Is Deprecated: Use 'Withunsafebytes≪R≫(...)

Swift 5. 'withUnsafeBytes' is deprecated: use `withUnsafeBytesR(...) instead

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.

Swift 5.0: 'withUnsafeBytes' is deprecated: use `withUnsafeBytesR(...)

In Swift 5 the withUnsafeBytes() method of Data calls the closure with an (untyped) UnsafeRawBufferPointer, and you can load() the value from the raw memory:

let value = data.withUnsafeBytes { $0.load(as: UInt32.self) }

(compare How to use Data.withUnsafeBytes in a well-defined manner? in the Swift forum). Note that this requires that the memory is aligned on a 4-byte boundary. For alternatives see round trip Swift number types to/from Data.

Note also that as of Swift 4.2 you can create a random 32-bit integer simply using the new Random API:

let randomId = UInt32.random(in: .min ... .max)

'withUnsafeBytes' is deprecated: use `withUnsafeBytesR(_: (UnsafeRawBufferPointer)

As per the in the doc

you can change with this

_document = data.withUnsafeBytes { ptr in
htmlReadMemory(ptr.baseAddress?.assumingMemoryBound(to: Int8.self), Int32(data.count), nil, nil, 0)

Related Topics

Leave a reply