13

Code that was previously working in Swift 2.2 is now throwing the following error in Swift 3:

enter image description here

Here is my code:

let tempData: NSMutableData = NSMutableData(length: 26)!
tempData.replaceBytes(in: NSMakeRange(0, data.count), withBytes:data.bytes)

What should I replace "data.bytes" with to fix the error? I've tried implementing 'withUnsafeBytes' and had a look at Apple's documentation, but can't get my head around it!

James Anderson
  • 556
  • 3
  • 16
  • 41
  • You haven't provided the source of `data`, but if you can convert that also to `Data`, this will all be much simpler and you won't need to bridge between `NSMutableData` and `Data`. You'll just use `replaceSubrange`. – Rob Napier Aug 16 '16 at 18:10

2 Answers2

13

Assuming that data has type Data, the following should work:

let tempData: NSMutableData = NSMutableData(length: 26)!
data.withUnsafeBytes { 
    tempData.replaceBytes(in: NSMakeRange(0, data.count), withBytes: $0)
}

using the

/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
public func withUnsafeBytes<ResultType, ContentType>(_ body: @noescape (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType

method of Data. Inside the closure $0 is a UnsafePointer<Void> to the bytes (UnsafeRawPointer in Xcode 8 beta 6).

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

Use this :

        let data:Data = Data()
        let myDataBytes = data.withUnsafeBytes {_ in
            UnsafePointer<UInt8>(data.withUnsafeBytes({
                $0
            }))
        }
        let writtenBytes = writeStream.write(.init(myDataBytes), maxLength: data.count)
闪电狮
  • 367
  • 2
  • 9