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: