Currently, the canImport statement in swift seems to only check if a module can be imported. But apparently it's not enough to know if something in a module can be imported.
For example, I've been playing around with compiling some projects requiring the arc4random_uniform
function from glibc.
The code in the project would simply check:
#if os(Linux)
import SwiftGlibc
func arc4random_uniform(...) ... {
...
}
#endif
This code will work on certain systems but it appears that the arc4
functions have been added to glibc since version 2.36.
In my case, I have the glibc version 2.39 on my system and the above code will fail because we're redefining a function to one that already exists in SwiftGlibc.
Obviously, checking for os(Linux) isn't enough to know if something you need exists or not. I think it's great that it's so easy to create a shim for something in swift but it's unfortunate that there doesn't seem to be good ways to determine if you need the shim or not.
For that reason, I was thinking that it would make sense to extend the canImport statement to match the import syntax.
This way, we could check if a specific symbol can be imported at all.
For example, the code above could be rewritten has:
#if !canImport(func SwiftGlibc.arc4random_uniform)
... define a shim for that specific symbol.
#endif
It would also make sense to be able to check that not only the symbol exists but also match a specific type.
#if !canImport(func SwiftGlibc.arc4random_uniform(UInt32) -> UInt32)
#endif
The canImport can be a much more powerful tool to check if a feature you need really exists and not just if a module exists.