Skip to content

Instantly share code, notes, and snippets.

@mayoff mayoff/convert.swift
Last active Jun 17, 2019

Embed
What would you like to do?
How to convert from DispatchData to Data without copying the bytes
import Dispatch
import Foundation
var x = 7
let dd = withUnsafeBytes(of: &x, { DispatchData.init(bytes: $0) })
print(dd as? Data) // Case 1: nil
print(dd as? NSData) // Case 2: nil
print(dd as Any as? Data) // Case 3: nil
print(dd as Any as? NSData) // Case 4: .some
print(dd as Any as? NSData as Data?) // Case 5: .some
let d = dd as Any as! NSData as Data
print(dd.withUnsafeBytes(body: { Int(bitPattern: $0) }) == d.withUnsafeBytes({ Int(bitPattern: $0) }))
// true
@mayoff

This comment has been minimized.

Copy link
Owner Author

mayoff commented Jun 8, 2018

UPDATE! It turns out this is the most efficient way to convert a DispatchData to a Data, both in source code size and in memory and CPU time:

let d = dd as AnyObject as! Data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.