NullHypothesis NullHypothesis - 5 months ago 62
iOS Question

Unsafe bytes in Swift 3

I'm writing a file to disk and I am in the process of converting my code to Swift 3, and got stuck on something. Wanted to see if someone could give me a push in the right direction.

My current code block is:

open let text: NSString
data = possibleData ?? Data()
open let fileURL: URL?
open let fileEncoding: String.Encoding?
fileprivate let data: Data!

text = NSString(bytesNoCopy: UnsafeMutableRawPointer(mutating: data.bytes.bindMemory(to: Void.self, capacity: data.count)), length: data.count, encoding: encoding.rawValue, freeWhenDone: false)!

Swift is saying that calling data.bytes is unavailable and to I need to use .unsafebytes instead. I don't grasp the way you invoke unsafe bytes (it's not as simple as switching bytes to unsafe bytes)

So I did a little research and some people have said to use a closure block like this:

data.withUnsafeMutableBytes {(bytes: UnsafeMutablePointer<UInt8>)->Void in
//work with bytes in here

My problem is, what do I put inside the closure block to get my above code working? I think I'm missing something fundamentally. I can't use bytes because it gives the same error again.

Anyone have any ideas? thanks!

Rob Rob

If you really need to use this pattern, assuming data was a var and not a let, you could do something like:

let text = data.withUnsafeMutableBytes { bytes in
    return NSString(bytesNoCopy: bytes, length: data.count, encoding: encoding.rawValue, freeWhenDone: false)!

Or, I don't know why you'd use NSString, so you could do:

let text = data.withUnsafeMutableBytes { bytes in
    return String(bytesNoCopy: bytes, length: data.count, encoding: encoding, freeWhenDone: false)!

Frankly, this whole pattern seems fragile (why forced cast? why using unsafe pointers rather than various safe patterns? etc.). If you're writing this to a file, so why wouldn't you just write the Data directly?

do {
    try data.write(to: fileURL)
} catch {
    print("Error: \(error.localizedDescription)")