Previous post Hashbang Swift: Part I covered Swift code running from the terminal as a script, using a Unix-like mechanism called hashbang (a.k.a. shebang, sha-bang or hash-exclam). One might have noticed that a Swift code run using that approach doesn’t import Frameworks, and that’s because
xcrun on that post launches
swift without specifying a SDK.
1 2 3 4 5 6
As mentioned on that post,
xcrun is also responsible for showing SDKs paths for iOS and Mac OS X development.
But unfortunately wrapping the call which returns the SDK path does not work on the hashbang declaration, making the elegant syntax below throw an error.
What is the simplest thing to do that could make it to work? (a question we ask ourselves a lot at work, when pair programming with TDD/BDD). In this case, the simplest thing to do would be to include the full SDK path in the hashbang declaration.
1 2 3 4 5 6 7 8 9 10 11
Another way to address this problem is by setting the SDK using the environment variable
SDKROOT, without setting the SDK within the script.
1 2 3 4 5
Like the first option, this one also works, but one needs to remember to set the
SDKROOT before running the script1.
A third option would be a helper file (
swiftHelper) that wraps all the
And since all the
xcrun calls are now wrapped, the hashbang needs to be changed to the following:
1 2 3 4 5
./swiftHelper is the helper file with its mode bits changed to make it executable. In this example, the helper file is located in the same directory of the Swift code (
To make it more generic and directory-agnostic, the helper file can now be moved to another directory which is set in the
$PATH with its hashbang declaration changed to
#!/usr/bin/env swiftHelper, without the
All the options above require something: option 1 requires the developer to update the path every time a new SDK is released; option 2 requires a SDKROOT variable to be set before running the script; and option 3 requires a helper file.
Given the fact that Apple updates its Operating Systems once a year, I wouldn’t mind adopting the first alternative. It works and doesn’t require external settings and dependencies. It also gives the ability to lock that file to a particular SDK version.
It can be set in
.bash_profile… but I personaly don’t like to set global environment variables in my environments.↩