How to create another instance of Data without copy

I have a usecase, where I have Data instance as Data is Value type copy will be created on assignment. I want to prevent copying for which I was using this Initializer of Data. Will it prevent copying?.

Interesting question to learn about the internals of Swift (may be you should also ask on Swift.org).

IMHO it is hazardous to try to guess what will be copied or not.

You seen this in the doc about the initialiser:

If the result is mutated and is not a unique reference, then the Data will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with let or ensure that no other references to the underlying data are formed.

I have a few questions:

  • when, in your code, would data be copied ?
  • what is the problem (too large data ?)
  • why not use a class type to be sure you pass reference

@Claude31 I can't use class type as this Data instance is provided to me by the OS whenever my Completion is been called w.r.t Receive.

Now I want to use this data instance in C++. For which basically I create a wrapper class over this and pass it as Opaque to C++.

Code Snippet


class DataHolder {

 init () {}
 public var data_wrapper : Data?
}
func ReceiveHandler (_ pContent : Data? ) -> UnsafeMutablePointer {

  // pContent is only valid inside scope of this function .

  // Create a instance of wrapper class

   var x = DataHolder.init ()

  // Copy being created here.
   x.data_wrapper = pContent

  return Unmanaged.passRetained (x).toOpaque ()

}

Problem is copy creation each time which i want to prevent.

I can't use class type as this Data instance is provided to me by the OS whenever my Completion is been called w.r.t Receive.

What API are you using here?

That matters because some networking APIs can return either Data or dispatch_data_t depending on how you call them.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How to create another instance of Data without copy
 
 
Q