Tech Reflect

Tech Reflect

Share this post

Tech Reflect
Tech Reflect
Creating command-line tool in Swift

Creating command-line tool in Swift

Chris Hynes - cricket's avatar
Chris Hynes - cricket
Mar 29, 2017
∙ Paid

Share this post

Tech Reflect
Tech Reflect
Creating command-line tool in Swift
Share

This question comes up often on Swift mailing lists. Once you learn Swift, you’ll get addicted and want to use it everywhere. It’s not quite as straightforward writing a script in Swift as it is in python or bash. However, there are lots of benefits.

  • It’s a great entry point into learning Swift for those that typically write scripts rather than applications

  • You want to execute a bunch of shell commands, but you can use Swift’s rich data structures, straightforward programming language, and the huge Cocoa API.

Here’s what you can do:

  • Launch Xcode

  • File > New > ProjectChoose macOS

  • Click on Command Line Tool

  • Name it and save the project

  • Click on main.swift in the sidebar

  • Replace the Hello, World line with this code.

import Foundation

struct Shell {
     func stripWhitespace(_ inString: String) -> String {
         return inString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
     }

     func executeCommand(_ command:String, echo: Bool = true) -> String {
         let process = Proce…

Keep reading with a 7-day free trial

Subscribe to Tech Reflect to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Christopher Hynes
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share