Scripting with Swift

Did you know that, just like Python, Bash scripts, etc., you can run a Swift source file right from the command-line as if it was an already compiled executable? You betcha! ๐Ÿ˜Ž The Swift REPL program honors the SHEBANG line in a Swift source file.

#!/usr/bin/swift
import Foundation

print("")
print(" Int8 - size: \(MemoryLayout<Int8>.size); stride: \(MemoryLayout<Int8>.stride); alignment: \(MemoryLayout<Int8>.alignment)")
print("Int16 - size: \(MemoryLayout<Int16>.size); stride: \(MemoryLayout<Int16>.stride); alignment: \(MemoryLayout<Int16>.alignment)")
print("Int32 - size: \(MemoryLayout<Int32>.size); stride: \(MemoryLayout<Int32>.stride); alignment: \(MemoryLayout<Int32>.alignment)")
print("Int64 - size: \(MemoryLayout<Int64>.size); stride: \(MemoryLayout<Int64>.stride); alignment: \(MemoryLayout<Int64>.alignment)")
print("  Int - size: \(MemoryLayout<Int>.size); stride: \(MemoryLayout<Int>.stride); alignment: \(MemoryLayout<Int>.alignment)")
print("")
print(" UInt8 - size: \(MemoryLayout<UInt8>.size); stride: \(MemoryLayout<UInt8>.stride); alignment: \(MemoryLayout<UInt8>.alignment)")
print("UInt16 - size: \(MemoryLayout<UInt16>.size); stride: \(MemoryLayout<UInt16>.stride); alignment: \(MemoryLayout<UInt16>.alignment)")
print("UInt32 - size: \(MemoryLayout<UInt32>.size); stride: \(MemoryLayout<UInt32>.stride); alignment: \(MemoryLayout<UInt32>.alignment)")
print("UInt64 - size: \(MemoryLayout<UInt64>.size); stride: \(MemoryLayout<UInt64>.stride); alignment: \(MemoryLayout<UInt64>.alignment)")
print("  UInt - size: \(MemoryLayout<UInt>.size); stride: \(MemoryLayout<UInt>.stride); alignment: \(MemoryLayout<UInt>.alignment)")
print("")
print("  Float - size:  \(MemoryLayout<Float>.size);  stride: \(MemoryLayout<Float>.stride);  alignment: \(MemoryLayout<Float>.alignment)")
print(" Double - size:  \(MemoryLayout<Double>.size);  stride: \(MemoryLayout<Double>.stride);  alignment: \(MemoryLayout<Double>.alignment)")
//print("Float80 - size: \(MemoryLayout<Float80>.size); stride: \(MemoryLayout<Float80>.stride); alignment: \(MemoryLayout<Float80>.alignment)")
print("")
print("timespec - size: \(MemoryLayout<timespec>.size); stride: \(MemoryLayout<timespec>.stride); alignment: \(MemoryLayout<timespec>.alignment)")
print("")

If you save the source above as “layout.swift” on a Linux system, give it executable rights (chmod a+x layout.swift), and, assuming you have installed Swift in the default location (/usr/), then simply typing “./layout.swift” at the command-line will cause Swift to load, compile, and then execute the program.

And it’s pretty darn quick about it too! Swift seems to do some kind of caching. Granted this isn’t a very big program but, once it ran the first time, it only took a second for it to launch and run on and ODROID C4!

Leave a Reply