Getting scripty

So as part of last month I was using Python to create a Static Site Generator. I wanted to see if I could use swift for scripting, too. The answer is a qualified yes.

See the swift-scripting repo for more details

Yes, one can pretty easily knock out a script

#!/usr/bin/env swift

    //    chmod +x swift_hello 
    //    ./swift_hello.swift apple banana kumquat

    // Outputs
    //     Number of arguments: 3
    //     Arguments:
    //     - apple
    //     - banana
    //     - kumquat

//https://theswiftdev.com/how-to-build-better-command-line-apps-and-tools-using-swift/

print("Hello, world!")

/// the very first element is the current script
let script = CommandLine.arguments[0]
print("Script:", script)

/// you can get the input arguments by dropping the first element
let inputArgs = CommandLine.arguments.dropFirst()
print("Number of arguments:", inputArgs.count)

print("Arguments:")
for arg in inputArgs {
    print("-", arg)
}

/// reading lines from the standard input
print("Please enter your input:")
guard let input = readLine(strippingNewline: true) else {
    fatalError("Missing input")
}
print(input)

Advantage over Python: C code can just be punked straight into these scripts, no questions asked.

Disadvantage over Python: Swift can’t really do multi-file “scripts” as effortlessly since Swift is a compiled language, but if you don’t want to bother with making a package the following will get you an executable without much fuss.

One just uses the code from one file in another other files, no import statement needed. No header file. Although tools like VScode and Xcode won’t really be able to help out with code completion.

When you have what you want it’s compile time:

compile with: swiftc *swift -o myappname where

for more info swiftc --help

or also swiftc `find . -name "*.swift" -maxdepth 1` -o myappname where

the result will be a new item, an executable, in the file directory which can then be run via the command line with ./myappname

otool -L ./myappname will print to the console all the libraries that the Linker believes are used of your app. The swiftc compile by default is a dynamic compile (vs static) so this is a lookup table. The files have not been copied into the app directory. swiftc -static-executable when compiling will do a static compile instead (if compiling for a non-Apple platform).

NOTE:tipsy-robot-swift i.e. the following weeks post has info on using a package.

January Wrap Up Tasks

Wrapped up the Nature of Code project doing things like

Site Meta