Coerce NSData to Data


(Ryan Lovelett) #1

I'm puzzeled by the behavior of the automatic coercion. Specifically
when something will work and when it will not. It at least has something
to do with the platform. That much I have tracked down.

I've attached a file, bridge.swift, that on Linux will fail to compile
with the error: cannot convert value of type 'NSData' to type 'Data' in
coercion. However, on Darwin it compiles just fine.

(The contents of the file just incase it gets stripped)

import Foundation

let md = NSData(bytes: [0x0D, 0x0A, 0x0D, 0x0A], length: 4)
_ = md as Data

On Linux the `md` has a method `_bridgeToSwift()` that returns the
`Data` I am looking for. But of course, the Darwin version does not.

Which begs the question what is the cross-platform way of doing things?
I'm hoping it is not `if #os(Linux)`...

bridge.swift (94 Bytes)


(Joe Groff) #2

The `as` bridging is generally an Objective-C bridging feature, and isn't present on Linux. On Linux, AIUI, you should use the value types as much as possible—this was a major motivation for the "id-as-Any" changes to the ObjC bridge on Apple platforms to enable that. Does Data have a regular initializer to construct from an NSData?

-Joe

···

On Oct 14, 2016, at 11:15 AM, Ryan Lovelett via swift-users <swift-users@swift.org> wrote:

I'm puzzeled by the behavior of the automatic coercion. Specifically
when something will work and when it will not. It at least has something
to do with the platform. That much I have tracked down.

I've attached a file, bridge.swift, that on Linux will fail to compile
with the error: cannot convert value of type 'NSData' to type 'Data' in
coercion. However, on Darwin it compiles just fine.

(The contents of the file just incase it gets stripped)

import Foundation

let md = NSData(bytes: [0x0D, 0x0A, 0x0D, 0x0A], length: 4)
_ = md as Data

On Linux the `md` has a method `_bridgeToSwift()` that returns the
`Data` I am looking for. But of course, the Darwin version does not.

Which begs the question what is the cross-platform way of doing things?
I'm hoping it is not `if #os(Linux)`...
<bridge.swift>_______________________________________________


(Ryan Lovelett) #3

Does Data have a regular initializer to construct from an NSData?

It does. I've gone ahead and refactored the code to just not use NSData.

Thanks!