On 22. des. 2017, at 8:48 f.h., Daryle Walker <[email protected]> wrote:
> I already have the code as an extension of Data. In C, we can use pointer
> type-punning shenanigans to convert between a dispatch_data_t and NSData*. To
> trigger this code in a test that I would write in Swift, DispatchData would
> need to be convertible to Data. Is there a way to do the conversion in
> Swift? It doesn’t seem obvious since DispatchData and Data are value types,
> not pointer nor reference types.
Although they are value types, DispatchData is immutable, so when Swift
(notionally) copies it to assign it to something else, it just gets another
reference to the same object. This does what I think you want (you can see from
the output that the enumerateBytes block is called for the two segments of the
Data):
> let buffer1: [UInt8] = [1,2]
> let buffer2: [UInt8] = [3,4,5,6]
>
> var data = DispatchData.empty
> data.append (buffer1.withUnsafeBytes { DispatchData (bytesNoCopy: $0) })
> data.append (buffer2.withUnsafeBytes { DispatchData (bytesNoCopy: $0) })
>
> let bdata = ((data as Any) as! NSData) as Data
>
> bdata.enumerateBytes { (bufp, pos, stop) in
> print("buffer at index", pos, "is", bufp)
> }
Casting the DispatchData to Any causes Swift to lose the static type
information, like casting it to (id) in objc. Downcasting that Any to NSData
causes it to check that the dynamic type is compatible (a small unnecessary
run-time cost, presumably equivalent to [data isKindOfClass:[NSData class]])
and to know that the value is statically an NSData. Then cast it to the Swift
Data type (which should be free).
You don't actually need all three casts, you can get by with two, but I think
that explicitly casting through NSData makes it clearer to the reader why
you're doing this dance, and I don't think it causes any more code to be
generated in the actual executable.
If Apple at some point in the future makes DispatchData no longer
toll-free-bridgable to NSData, this will fail at runtime (the as! will throw).
Of course it would be preferable for it to fail at compile-time, but until the
DispatchData type is correctly annotated, this will have to do.
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]