Search code examples
iosswiftmacosconditional-compilation

Swift availability check exclude macOS


I have a code in my app which I want to execute on iOS 13 or later. So, I was using a standard availability check:

if #available(iOS 13.0, *) {
    return Color.systemGray6.resolvedColor(with: trait!)
} else {
    return Color(red: 0.082, green: 0.118, blue: 0.161, alpha: 1.0)
}

Color is a typealias which casts to UIColor on iOS and NSColor on macOS. I am kind of trying to create macOS version of my target with as little if..else as possible.

The code above should work as NSColor has many of the same init methods as UIColor. The problem is that when I build my macOS target it complains about systemGray6. So, for a reason unknown to me, macOS target passes #available(iOS 13.0, *) check!

Why does it happen and how can I prevent it?


Solution

  • When you use if #available(iOS 13.0, *) you're basically saying: do this on iOS 13.0 and later, and on all other operating systems - that's what the * means.

    In your specific case, you'll need to exclude macOS, since NSColor does not have the systemGrayX getters:

    #if os(iOS)
    if #available(iOS 13.0, *) {
         return Color.systemGray6
    }
    #endif
    return Color(red: 0.082, green: 0.118, blue: 0.161, alpha: 1.0)