Manual Memory Management

suggest change

When interfacing with C APIs, you may need to step outside Swift's reference counting. Unmanaged is the tool for that.

If you need to supply a type-punned pointer to a C function, use the toOpaque method of Unmanaged to obtain a raw pointer, and fromOpaque to recover the original instance:

func setupDisplayLink() {
  let pointerToSelf: UnsafeRawPointer = Unmanaged.passUnretained(self).toOpaque()
  CVDisplayLinkSetOutputCallback(self.displayLink, self.redraw, pointerToSelf)
}

func redraw(pointerToSelf: UnsafeRawPointer, /* args omitted */) {
  let recoveredSelf = Unmanaged<Self>.fromOpaque(pointerToSelf).takeUnretainedValue()
  recoveredSelf.doRedraw()
}

Note that, if using passUnretained and counterparts, it’s necessary to take all precautions as with unowned references.

To interact with legacy Objective-C APIs, you may need to change an object's reference count by hand. Unmanaged has retain and release for that. Prefer passRetained and takeRetainedValue, which retain or consume a retain before returning:

func preferredFilenameExtension(for uti: String) -> String! {
  let result = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension)
  guard result != nil else { return nil }

  return result!.takeRetainedValue() as String
}

These solutions should always be a last resort. Prefer a language-native API when one exists.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents