Search code examples
iosswiftimportframeworks

How do you selectively import a framework in Swift?


I have a shared framework that needs to be used by iOS and tvOS, but I want to selectively import a framework for iOS only (CoreTelephony). The swift grammar says you can prepend an attribute, but this doesn't work:

@available(iOS 10.0, *) import CoreTelephony

Is this simply not supported? Do I need to subclass just to import the iOS specific framework?


Solution

  • For Swift <= 4.0 you can use the os() configuration test function:

    #if os(iOS)
      import CoreTelephony
    #endif
    

    You'll have to wrap code that uses CoreTelephony as well.

    All available tests for os() are: macOS, iOS, watchOS, tvOS, Linux, Windows, and FreeBSD.

    For Swift >= 4.1 you can also use canImport():

    #if canImport(CoreTelephony)
      import CoreTelephony
    #endif