Using canImport with submodules and specific types

As it stands, these import statements are all valid Swift:

import UIKit
import UIKit.UITableViewController
import class UIKit.UITableViewController

However, only the first maps to using canImport():

#if canImport(UIKit)
…
#endif

I’m currently in a situation where a client of a library I’m writing may choose to import only part of the library using CocoaPods subspecs. Right now, in order to allow for conditional compilation of this, I’d have to define additional Swift flags in the client app like so:

#if HAS_SUBSPEC_A_IMPORT
…
#endif

What I would like to propose is a slight modification of canImport to allow it to work with anything that the import statement does, whether it’s submodules, struct, classes, protocols, or what have you. This would allow this type of code:

#if canImport(class MyLibrary.SpecificClass)
…
#endif

Conditional compilation would then work automatically for any consumer of the code that imported the correct Swift libraries. Would there be any downsides to this approach? Would this need to go through the full SE process or is this a straight enhancement to canImport?

Seems harmless and useful, rather than harmful and useless. :slight_smile:

1 Like