[swift-evolution] [Review] SE-0075: Adding a Build Configuration Import Test

Patrick Smith pgwsmith at gmail.com
Fri May 13 02:42:36 CDT 2016


> canImport (or whatever it ends up being called) is deliberate.
> 
> You test before you import:
> 
> #if canImport(x)
>    import x
> #else
> ...
> #endif
> 
> and you test at the use-site
> 
> #if canImport(x)
>   // use things that are available in x
> #else
> ...
> 
> So you don't import UIKit unless you *can*, and you don't use UIColor unless you can import UIKit. This follows closely on the design of __has_include.
> 
> -- E


I guess one issue I can see is it’s used in two different ways:
- The first use of canImport is used to check whether it can import a module, and then does so, but there’s no requirement for it to do so. Is this the right this to do?
- The second use of canImport makes no guarantee that the module has been imported, only that it can.

What if instead `import` could return whether it imported or not, when used with #if? Instead of ‘can import’, you get ‘did just import’ and ‘has imported’.


import Required // Error if not present, current behaviour

#if import CoolThing // Skips code block if not present, imports otherwise
  // Do something with CoolThing module
#else
  import AlmostAsCoolThing
#endif

and you test at the use-site

#if module(X) // Does not import, only checks if it has been imported
  // use things that are available in X
#else


As per Pyry’s feedback, you could add a version:

#if import Frobnication(<1.7.3) // <- Only added version constraint here.
extension Knob : Frobnicatable { ... }
#endif



Just a way to make it less low level.



More information about the swift-evolution mailing list