Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Import packages depending from OS version

When I’m writing a code, I can use @available and #available directives, e.g.:

@available(watchOS 10.0, *)
    class ClassWhichUsesNewfunctions: NSObject {
}

but they doesn’t work in import section. Obviously, I want my app could be used on previous OS versions too, so I can’t simply change target’s destination.

I tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if #available(watchOS 10.0, *){
    import WorkoutKit
}

and

@available(watchOS 10.0, *)
import WorkoutKit

but both of them gives compilation errors Statements are not allowed at the top level and '@available' attribute cannot be applied to this declaration

So how could I import newest packages? Thank you in advance.

>Solution :

There is another way, you can use the canImport macro in this circumstance. i.e

#if canImport(WorkoutKit)
import WorkoutKit
#else
import Foundation
#endif

func doStuff() {
    #if canImport(WorkoutKit)
    print(SingleGoalWorkout(activity: .bowling))
    #else
    print("No workout here")
    #endif
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading