Getting Started With Multi File Command Line Swift
I wanted to write a post on commandline swift projects that span more than one file. This post covers a hello world type example that spans three files and prompts for input. Also covered are a file wrapper for multi file swift scripts and compiled command line executables.
Also see the post on Getting Started With Command Line Swift.
Software Versions
$ date
February 9, 2016 at 02:08:36 AM JST
$ uname -mv
Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64 x86_64
$ swift --version # swiftc is the same
Apple Swift version 2.1.1 (swiftlang-700.1.101.15 clang-700.1.81)
Target: x86_64-apple-darwin15.3.0
$ xcrun --version
xcrun version 28.
Instructions
First, we will create a multi file project.
Add the following to main.swift.
func main() {
let name = inputPrompt("What is your name? ")
sayHello(name)
}
main()
Add the following to input_prompt.swift.
import Foundation
func inputPrompt(message: String = "> ") -> String {
print(message, terminator: "")
fflush(__stdoutp)
let keyboard = NSFileHandle.fileHandleWithStandardInput()
let inputData = keyboard.availableData
let result = NSString(data: inputData, encoding: NSUTF8StringEncoding) as! String
return result.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
}
Add the following to hello.swift.
func sayHello(name: String) {
print("Hello, " + name + "!")
}
To execute main.swift and the support files, create a wrapper script. Add the following to hello_user.sh.
#!/bin/sh
TMPFILE=`mktemp /tmp/Project.swift.XXXXXX` || exit 1
trap "rm -f $TMPFILE" EXIT
cat *.swift > $TMPFILE
swift $TMPFILE
Make the wrapper executable.
chmod +x hello_user.sh
The wrapper script can be run from the command line.
./hello_user.sh
Alternatively, compile the files into an executable with swiftc.
swiftc file_a.swift file_b.swift file_c.swift -o executable_name
One of the files in this project imports foundation, so xcrun -sdk macosx swiftc needs to be used instead of swiftc.
xcrun -sdk macosx swiftc main.swift input_prompt.swift hello.swift -o hello_user
The executable can be run from the command line.
./hello_user
References:
- Swift, Getting Started With Command Line Swift
- Swift, Is there a way to have a Swift script use multiple files
- Swift, How to include .swift file from other .swift file in an immediate mode?
- Swift, Scripting in Swift is Pretty Awesome
- Swift, How to write small command line scripts in Swift
- Swift, Minimal Swift command line Hello World
- Swift for CLI tools
- Swift, Functions
- Swift, Input from the keyboard in command line application
- Swift, ‘Use of Unresolved Identifier’ in Swift
- Swift, print without newline in swift 2.0
- Swift, Update current line with command line tool in Swift
- Swift, Does swift has trim method on String?