[swift-users] Coerce NSData to Data
jgroff at apple.com
Fri Oct 14 17:19:09 CDT 2016
> On Oct 14, 2016, at 11:15 AM, Ryan Lovelett via swift-users <swift-users at 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)`...
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?
More information about the swift-users