Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark Swift declaration as available in iOS and unavailable in macOS

Tags:

swift

I have a class that only works on iOS 10.0 and up. It's in a Swift package, so Xcode 11 is trying to compile it for macOS too, and complaining. How do I say that it's available on iOS 10.0 only.

These don't work:

@available(iOS 10.0, *)
class Thing { ... }

@available(macOS, unavailable)
@available(iOS 10.0, *)
class Thing { ... }

Some docs: https://docs.swift.org/swift-book/ReferenceManual/Attributes.html

like image 567
Rob N Avatar asked Oct 29 '25 12:10

Rob N


2 Answers

From docs

iOS iOSApplicationExtension macOS macOSApplicationExtension watchOS watchOSApplicationExtension tvOS tvOSApplicationExtension swift You can also use an asterisk (*) to indicate the availability of the declaration on all of the platform names listed above.

So * in @available(iOS 10.0, *) saying that declaration is available in all the other platforms. But we are also specifying that it is not available in macOS. So in the end compiler gets confused and availability wins the war. Instead of using @available you can use compiler flags,

#if os(iOS)
#endif

to specify the compiler to compile code only on iOS.

like image 68
Shreeram Bhat Avatar answered Oct 31 '25 04:10

Shreeram Bhat


Wrap it inside this

#if canImport(UIKit)
    // iOS Only code
#endif

This way, the code is excluded from compilation when the target platform doesn’t support UIKit.

You can also check with the OS type directly using #if os(iOS) or #if !os(macOS), BUT! ask yourself: why do you care about the OS? Is it because you’re using something specific to iOS like UIKit? If so, use canImport(UIKit). If not, then be more general and limit platforms using the OS check.

like image 39
Mojtaba Hosseini Avatar answered Oct 31 '25 02:10

Mojtaba Hosseini