Is there an opposite of @available?

I got tried of the compiler telling me that .onChange(of:) was deprecated, so I thought, find, I'll simply stub it out for the older versions. Only... I can't seem to do that? I can use @available(macOS 14, *) to build for that and later, but is there any way to do the opposite? (I'd hoped there was a #if available support, but there isn't.)

Replies

I'm using Objective-C++, and I don't know how this translates to Swift, but I use a pattern like this:

if (@available( macOS 10.15, * ))
{
    // do it the new way
}
else
{
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wdeprecated-declarations"
    // do it the old way
    #pragma clang diagnostic pop
}

This is at the declaration level, not in-function level.

Eg.,

extension View {
#if os(macOS)

    @ViewBuilder func onChange<V>(
        of value: V,
        initial: Bool = false,
        perform action: @escaping (V, V) -> Void
    ) -> some View where V : Equatable {
        onChange(of: value) { n in
            action(value, n)
        }
    }
#endif
}

Is @unavailable what you are looking for : https://github.com/apple/swift-evolution/blob/main/proposals/0290-negative-availability.md

It is now possible to write inverted availability conditions by using the new #unavailable keyword:

if #unavailable(iOS 15.0) {
    // Old functionality
} else {
    // iOS 15 functionality 
}
  • I think @unvavailable would do the trick, but #unavailable does not -- as I said above, it's for a declaration not in-function code. However, that proposal doesn't actually discuss @unavailable.

Add a Comment

You should be able to use #else

  • Except you cannot use either @available or #available in a #if.

Add a Comment