A Swift command-line tool builds on a Mac but fails on Linux; which Apple-only pieces usually break, and how do you guard them?
answer
- no Objective-C runtime off Apple
- Darwin is not the C library there
- networking split into its own module
- test capability, not the platform name
basics
~20 sOff Apple platforms Swift has no Objective-C runtime, no Apple frameworks and a different C library, so @objc, #selector, Darwin imports and URLSession without FoundationNetworking break; guard them with canImport checks or replace them with plain Swift.
solid answer
~40 sSwift on Linux omits everything related to Objective-C, so `@objc` fails with "Objective-C interoperability is disabled", `#selector` and `#keyPath` fail with "can only be used with the Objective-C runtime", and KVO through `@objc dynamic` is gone; replace them with closures, delegates or plain `dynamic`. Apple-only frameworks such as UIKit or Combine give "no such module", and `import Darwin` must become `Glibc` (or `Musl` with the Static Linux SDK). Foundation itself exists: since Swift 6 Linux uses the same Swift implementation of `JSONDecoder`, `URL`, `Calendar` and friends as macOS 15, but `URLSession` sits in a separate `FoundationNetworking` module backed by libcurl. Guard each with `#if canImport(FoundationNetworking)`, `canImport(Glibc)` or `_runtime(_ObjC)`, and add a Linux CI job so the next break shows up in review, not in production.
code
swift · 29 linesimport Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking // URLSession on Linux, backed by libcurl
#endif
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc // most Linux distributions
#elseif canImport(Musl)
import Musl // the Static Linux SDK
#endif
final class Poller {
let request = URLRequest(url: URL(string: "https://example.com/health")!)
var onTick: (() -> Void)? // a closure instead of target/#selector
func tick() { onTick?() }
}
#if _runtime(_ObjC)
let runtime = "Objective-C runtime present"
#else
let runtime = "no Objective-C runtime"
#endif
let poller = Poller()
poller.onTick = { print("tick at", time(nil)) }
poller.tick()
print(runtime)go deeper
Recall that Linux has no Objective-C runtime and no Apple frameworks, so @objc, #selector and imports such as UIKit cannot compile there.
Explain the guards: canImport for FoundationNetworking and the C library, _runtime(_ObjC) for Objective-C-only paths, and why Foundation's core types now behave the same on both platforms.
Show how you make a port stick: a Linux container job in CI, capability checks instead of OS checks, and Objective-C patterns replaced with closures rather than hidden behind conditions.
Decide whether portability is a requirement for a module at all; making it portable costs a Linux CI lane and design limits, which pay off only if the code really runs off Apple platforms.
## Why code that builds on a Mac can fail on Linux On Apple platforms a Swift program sits on top of the **Darwin** C library, the **Objective-C runtime** and a large set of Apple frameworks. On Linux none of those exist. The Swift compiler, the standard library and the concurrency runtime are the same, and since **Swift 6** so is most of Foundation, but the layers underneath differ. Most porting failures fall into four groups. | Mac assumption | On Linux | Typical fix | |---|---|---| | Objective-C runtime | absent | closures, delegates, plain Swift `dynamic` | | Apple frameworks (UIKit, Combine, …) | absent | `#if canImport(…)` or a portable dependency | | `import Darwin` | `Glibc` (most distributions), `Musl` (Static Linux SDK) | `canImport` chain | | `URLSession` from `import Foundation` | lives in `FoundationNetworking` | conditional extra import | ## 1. No Objective-C runtime Swift's own interop notes say it plainly: on platforms without Objective-C interop, **Swift omits everything related to Objective-C**. The compiler rejects the constructs that need it: - `@objc` on a method or property: `error: Objective-C interoperability is disabled`. - `#selector(...)`: `error: '#selector' can only be used with the Objective-C runtime` (and the same wording for `#keyPath`). - Key-value observing through `@objc dynamic` properties, target–action wiring and `perform(_:)`-style messaging have nothing to run on. Plain Swift `dynamic` (without `@objc`) still compiles, and closures or a small protocol replace target–action. When a Mac-only path must stay, wrap it in `#if _runtime(_ObjC)`, which is true exactly where the Objective-C runtime exists. ## 2. Frameworks and the C library - An import of an Apple-only module fails with `error: no such module 'Combine'` (or whichever module). Guard it with `#if canImport(Combine)` and provide the portable path in the `#else`. - C functions such as `time`, `getenv` or `strerror` come from `Darwin` on Apple, `Glibc` on most Linux distributions, `Musl` when building with the Static Linux SDK, `WASILibc` for WebAssembly and `CRT` on Windows. swift-foundation's own sources use a `canImport` chain for exactly this. - Imported C signatures can differ between C libraries: a parameter may be `Optional` in one and not in another, or a pointer may import as `OpaquePointer` instead of `UnsafePointer<T>`. ## 3. Foundation off Apple platforms Swift 6 unified Foundation: `JSONDecoder`, `URL`, `Calendar`, `FileManager`, `ProcessInfo` and more are the same Swift implementation on Linux, Windows, macOS 15 and iOS 18. The open-source Foundation is split into modules: - **FoundationEssentials**: core types (`Data`, `Date`, `UUID`, `JSONEncoder`, `JSONDecoder`, `Predicate`) without internationalization data; import it alone when binary size matters. - **FoundationInternationalization**: locale-aware formatting backed by ICU. - **FoundationNetworking**: `URLSession` and friends, backed by libcurl; on Linux you must import it in addition to Foundation. - **FoundationXML**: XML support backed by libxml2. `import Foundation` on Linux brings in the essentials and the internationalization layer together, which is why most code just works, and why networking code is the classic exception. ## Guarding: test capabilities, not platform names 1. Prefer `#if canImport(Module)` over `#if os(Linux)`: it keeps working on Windows, Android or a new distribution without editing the condition. 2. Use `#if _runtime(_ObjC)` only around code that genuinely needs Objective-C. 3. Keep `#if os(...)` for behaviour that really is per-OS (file paths, signals). 4. Run the test suite in a Linux container in CI: the Mac build cannot reveal any of these failures, because every condition above is true there. ## A porting order that works 1. Build the tool in a Linux container first; swift.org publishes official container images, so this needs no Linux machine. 2. Fix the imports: Apple-only modules behind `canImport`, the C library chain, FoundationNetworking. 3. Replace Objective-C patterns with closures, delegates or protocols instead of hiding them behind conditions, so the Linux path is not a stub. 4. Fix C-signature differences the compiler reports, such as a C function whose result imports as `Optional` under one C library and non-optional under another. 5. Run the full test suite on Linux and keep that job in CI. ## What is not a porting problem The language itself does not change: generics, actors, `async`/`await`, `Codable` and the Swift 5 or Swift 6 language mode behave identically, because the compiler is the same. Server frameworks such as Vapor and Hummingbird run on Linux and macOS alike; their APIs are a separate subject.
- Why is #if canImport(FoundationNetworking) better than #if os(Linux) around the networking import?It tests the thing you need. FoundationNetworking also exists on Windows, and on Apple platforms `URLSession` is in Foundation itself, so the import is only needed exactly where the module exists. An `os(Linux)` check would miss Windows and break the day another platform gains the module.
- When would you import FoundationEssentials instead of Foundation in a Linux tool?When binary size or startup matters and the tool needs only core types such as `Data`, `Date`, `UUID` and `JSONDecoder`. FoundationEssentials omits the internationalization data that FoundationInternationalization brings in, so a small command-line tool or a statically linked binary gets much smaller. Guard it with `canImport(FoundationEssentials)` so the Mac build falls back to Foundation.
- Says Foundation is unavailable on Linux, so all Foundation code must be rewritten.
- Expects @objc to compile on Linux because NSObject-style APIs exist there.
- Guards every difference with os(Linux) instead of canImport.
- Believes the Swift 6 language mode behaves differently on Linux.
- Assumes URLSession comes in with a plain import Foundation on Linux.
Assumes Swift 6.4 toolchains; Swift 6.0 brought the unified Swift implementation of Foundation and the FoundationEssentials module to Linux and Windows.