Hi,
I have a network stream which I want to send data. I had an original few lines (copied from an example) which seemed to do the job, but gave the Xcode warning. After a couple of days I'm seemingly going round in circles, and down the deadend of empty documentation ('No overview available' on withUnsafeBytes).
Is my refactored verison correct? Both versions of 'write' work, as in the remote endpoint gets the data. But..
1. in the second version, withUnsafeBytes should be a throwing function so I presume that I'm not actually using the correct method?
2. in the first version the Int is returned by .write(), but this was never returned in the second version. What am I not understanding?
func sendMessage(msg: String) {
if var data = msg.data(using: .utf8) {
// original
// WARNING: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
let dataSent = data.withUnsafeBytes({
self.outputStream?.write($0, maxLength: data.count)
})
print("dataSent: \(String(describing: dataSent))")
// refactored
// pointer type chicanery, and method signatures from the Apple docs:
// Data: func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType
// OutputStream: func write(_ buffer: UnsafePointer, maxLength len: Int) -> Int
data.withUnsafeBytes({
let unsafeBufferPtr = $0.bindMemory(to: UInt8.self)
if let unsafePtr = unsafeBufferPtr.baseAddress {
let dataSent2 = self.outputStream?.write(unsafePtr, maxLength: $0.count)
print("dataSent2: \(String(describing: dataSent2))")
}
})
}
}
thanks,
1. in the second version, withUnsafeBytes should be a throwing function so I presume that I'm not actually using the correct method?
You are mistaking something. Both `withUnsafeBytes` are declared as `rethrows`.
Old
public func withUnsafeBytes<resulttype, contenttype="">(_ body: (UnsafePointer) throws -> ResultType) rethrows -> ResultType
New
@inlinable public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType
No change about throwing. So, throwing cannot be a clue to judge if you are using the correct method or not.
2. in the first version the Int is returned by .write(), but this was never returned in the second version. What am I not understanding?
In your first version, you have only one expression inside the closure passed to `withUnsafeBytes`. So swift applies implicit return feature.
The second version, you have one declaration and one if-statement. You may need to put an explicit return statement in such a case.
You may not be understanding the implicit return feature of Swift closures.
Please check the part Implicit Returns from Single-Expression Closures of the Swift book in Closure Expressions carefully.