Search code examples
swiftlinuxswift5

How can I use Foundation's URLRequest type on Linux?


When I try to use the struct URLRequest from Foundation, I get an error when compiling with swift 5.1.1. The same code works fine with swift 5.0.1.

Example: given file Foo.swift with content

import Foundation
print(URLRequest.self)

With Swift 5.0.1 we get

$ docker run --rm -v "$PWD:/app" swift:5.0.1 sh -c \
     'swiftc /app/Foo.swift && ./Foo'
URLRequest

But with 5.1.1

$ docker run --rm -v "$PWD:/app" swift:5.1.1 sh -c \
     'swiftc /app/Foo.swift && ./Foo
Foo.swift:2:7: error: use of unresolved identifier 'URLRequest'
print(URLRequest.self)
      ^~~~~~~~~~

I can't seem to find anything mentioning relevant changes to Foundation, and the source code at https://github.com/apple/swift-corelibs-foundation looks stable, too.

What's going on here, and is there a workaround for this?


Solution

  • This is caused by a recent move of networking related objects into a new FoundationNetworking module. The new module does not exists on Darwin, so one must use preprocessor commands to make code work on all supported platforms:

    import Foundation
    #if canImport(FoundationNetworking)
    import FoundationNetworking
    #endif
    
    print(URLRequest.self)
    

    This code compiles fine with both docker commands given above.