Skip to content

Instantly share code, notes, and snippets.

@matthewspear
Last active May 5, 2016 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewspear/5733f5ede43c9e3c93a090116bc3214a to your computer and use it in GitHub Desktop.
Save matthewspear/5733f5ede43c9e3c93a090116bc3214a to your computer and use it in GitHub Desktop.
Commandline Swift Script - use 'xcrun -sdk macosx swiftc SimpleArraySum.swift'
import Foundation
// Setup Standard Output, Error
let stderr = NSFileHandle.fileHandleWithStandardError()
let stdout = NSFileHandle.fileHandleWithStandardOutput()
func writeToStd(handle: NSFileHandle, _ str: String)
{
if let data = str.dataUsingEncoding(NSUTF8StringEncoding)
{
handle.writeData(data)
}
}
// Check if > 1 input argument
if Process.arguments.count < 2
{
// Expecting a string but didn't receive it
writeToStd(stderr,"Expecting string argument!\n")
writeToStd(stderr,"Usage: \(Process.arguments[0]) [list of numbers]\n")
exit(EXIT_FAILURE)
}
// Create Int array from arguments
var numbers: [Int] = []
for arg in 1..<Process.arguments.count
{
let input = Process.arguments[arg]
if let num = Int(input)
{
numbers.append(num)
}
else
{
writeToStd(stderr,"Input required to be of type Int\n")
exit(EXIT_FAILURE)
}
}
// Sum and print to stdout
var sum = 0
for num in numbers
{
sum += num
}
writeToStd(stdout, "\(sum)\n")
exit(EXIT_SUCCESS)
@matthewspear
Copy link
Author

Reference: Building Command Line Tools With Swift as my starting point on the writeToStd function!!

@Moximillian
Copy link

If you want to use swift as an alternative to shell scripts, then you don't really need that xcrun stuff. Only put the line below as the first line in the .swift file
#!/usr/bin/swift

and change the swift file to be executable
chmod o+x SimpleArraySum.swift

and you can run it directly
./SimpleArraySum.swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment