- Proposal: SE-00XX
- Author(s): Erica Sadun
- Status: TBD
- Review manager: TBD
This proposal introduces an if platform(...)
test to determine whether code is running on a platform family, such as Apple, Windows, Unix, etc.
This proposal was discussed on-list in the Adding an Platform-testing Build Configuration Test thread.
As Swift expands to a growing developer base and to new platforms, the existing suite of configuration tests begins to show strain. Shortcuts taking advantage of current limitations introduce fragility.
For example, testing #if os(iOS) || os(OSX) || os(watchOS) || os(tvOS)
to determine
whether code is running on an Apple platform may miss new platform targets and #if !os(Linux)
may introduce errors as Swift extends to other non-Apple platforms, such as Windows.
Testing specifically for an Apple, Unix, or Windows platform will enable the Swift development team to move past potentially fragile tests. Dmitri Gribenko writes, "There's a direction that we want to move to a unified name for the libc module for all platform, so "can import Darwin" might not be a viable long-term strategy."
#if platform(platform-name)
I propose a minimum suite of Apple, Windows, Linux, and Unix, where Unix will be true on both Apple and Linux targets.
Swift currently supports the following configuration tests:
- The literals
true
andfalse
- The
os()
function that tests forOSX, iOS, watchOS, tvOS, Linux, Windows, and FreeBSD
- The
arch()
function that tests forx86_64, arm, arm64, i386, powerpc64, and powerpc64le
- The
swift()
function that tests for specific Swift language releases, e.g.swift(>=2.2)
There are no alternatives considered.
Dmitri Gribenko:
It is not that I'm saying that there is no good use case, it is just that they are not obvious to me. Here's something I could imagine happening:
#if platform(Unix)
use system()
#else if platform(Windows)
use CreateProcessEx
#else
#error "unknown platform"
#endif
But I'm not sure that "Unix-like" and "Windows-like" are precise enough to write the kinds of checks you would want to write in low-level code.
See thread