Swift 5. 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(...) 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.
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.