How to Check if on Apple (macOS, iOS, tvOS, watchOS, and possible now possibly iPadOS) in a simplified form

Hi,

I was wondering if there is a simplified way of checking if my code was being built on an Apple OS (macOS, iOS, tvOS, watchOS) or not.
The reason for this is because sadly there are still some differences between the Apple Swift and the Open Swift. A good recent example of this, in Swift 5.1, is that Process.currentDirectoryURL has a slightly different value type. In Apple Swift its Process.currentDirectoryURL: URL? where as in Open Swift it's Process.currentDirectoryURL: URL

Currently to combat this I use the #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS). OR more recently I've been switching to #if _runtime(_ObjC). However I believe this to be unsafe because I'm sure its not a public function and could be removed at any moment.

I was hoping there was a simplified #if os(appleOS) or #if runtime(apple) or something like that which would be an indication that the code was being built within Apple Swift SDK

Any help/suggestions would be greatly appreciated.

While the following are technically distinct in meaning from a theoretical #if vendor(Apple), all of them work as practical substitutes:

#if canImport(ObjectiveC)
#if canImport(Darwin)
#if canImport(SwiftUI)


#if canImport(ā€¹Moduleā€ŗ) is generally the better choice over #if os(ā€¹OSā€ŗ) when guarding use of a particular import, but it doesnā€™t (directly) help with more fineā€grained things like differing return types.

It's a bug in swift-corelibs-foundation if we have a property with a type that's not the same as Darwin, with very narrow exceptions. Can you write it up on bugs.swift.org?

3 Likes