Data(contentsOf:) and new swift Foundation

When using the most recent swift 6.0 jammy nightly which includes the new swift-foundation

let data = try Data(contentsOf: URL(string: "https://swift.org")!)

Now throws an error The specified URL type isn’t supported.

Is this intended or something that will get rectified? I can see how you might want to discourage such a blocking operation in async code, but removing this will cause pain for some people.

And the type of unsupported URL should really be part of the error message (presumably http/https in this case). Also, this should be "URL scheme", not "URL type". Also, including the supported URL schemes would be nice.

1 Like

It seems like intentional behaviour based on the commit from May that added it. It's conditionalised so it only rejects non-file URLs if on a non-Darwin platform.

Maybe the change was made to address a layering problem, because FoundationNetworking is not necessarily always available on a Linux platform? But it also probably just ensures better code correctness going forward because loading network files through that inconspicuous Data initialiser was always a bit of a footgun.

2 Likes

I think we can add this functionality back in via an "up call" from FoundationEssentials into FoundationNetworking (when present). There's no doubt it surprises some people that it loads more than file URLs, on any platform, but you are probably also right that some might rely on it.

4 Likes

I filed a bug here.

2 Likes