6 C
New York
Saturday, March 22, 2025

ios – How do I conditionally compile swift primarily based on swift model and goal SDK?


I need to have the ability to conditionally compile blocks of swift code primarily based on the model of the swift language and the model of the goal SDK utilized by the construct system. I’ve no management over the person’s construct system. I discover on mine the next command line arguments are handed to the compiler by Xcode: -swift-version 5 and -target-sdk-version 14.2. So I hoped for one thing like the next, however I can not determine it out.

#if swift-version >= 5
    ...swift code...
#else
    ...previous method...
#endif


#if target-sdk-version >= 14.2
    ...swift code...
    ...maybe utilizing #accessible if deployment sdk is older...
#else
    ...previous method...
#endif

Here is a easy instance. Suppose I’ve a SwiftUI scene that I wish to apply the modifier .restorationBehavior(.disabled) However that is solely accessible within the SDK 15.0 and later. What ought to the supply code appear to be if I need simply the default habits if one is constructing in opposition to an older SDK?

Here is one futile try to make a Scene modifier that may simply be used like this .pleaseDisableRestoration()

extension Scene {
@accessible(swift, launched: 6.0)
    func pleaseDisableRestoration() -> some Scene {
        if #accessible(macOS 14, *) { //run time verify
            return self.restorationBehavior(.disabled)
        }else{
            return self
        }
    }

@accessible(swift, obsoleted: 6.0)
    func pleaseDisableRestoration() -> some Scene {
        return self
    }
}

It fails for 2 causes: (1) the self.restorationBehavior modifier is not going to compile if I am utilizing Swift 5, regardless that the declaration is marked for Swift 6 and later; and (2) the reuse of the declaration pleaseDisableRestoration will not work regardless that there isn’t a overlap within the Swift variations they apply to.

As DonMag factors out I can use #if swift(>=6.0) for half the issue. Sadly, the vital case is the SDK stage. However the instance above rewritten utilizing…

@accessible(macOS, launched: 15.0)
...
@accessible(macOS, obsoleted: 15.0)
...

…fails in the identical manner.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles