Easy methods to construct higher command line apps and instruments utilizing Swift?


The following tips will assist you to create superb CLI instruments, utility apps, server facet initiatives or terminal scripts utilizing the Swift language.


Working Swift information as scripts

It’s doable to run a Swift file straight from the command line for those who add a hashbang to the start of the file. This fashion you do not have to manually compile the code utilizing the swiftc command. You may merely give the file the executable permission flag and the system will name the Swift REPL underneath the hood, so our app will be evaluated mechanically. ?

#!/usr/bin/env swift

print("Hey, world!")

For instance this most important.swift file above will be marked as an executable file, and we will merely name it by way of the ./most important.swift command in a while (you simply have to make use of chmod just one time).

chmod +x most important.swift 
./most important.swift  

The fantastic thing about this technique is that you could quickly check your Swift command line snippets. You may even place the completed Swift scripts underneath the /usr/native/bin/ listing with out the swift file extension to make them obtainable “globally” on your working system person. ?

Utilizing command line arguments in Swift

The CommandLine enum makes it very simple to fetch the arguments handed to our Swift software or script. You may entry each argument utilizing the arguments variable as an array of Strings, however it’s also doable to get the uncooked knowledge utilizing the argc and unsafeArgv properties.

#!/usr/bin/env swift

let script = CommandLine.arguments[0]
print("Script:", script)

let inputArgs = CommandLine.arguments.dropFirst()
print("Variety of arguments:", inputArgs.rely)

for arg in inputArgs {
    print("-", arg)

It is best to observe that the primary argument is all the time the trail of the present script, so in case you are solely searching for the enter arguments you should use the dropFirst() technique to return a subset of the enter strings. Often every argument is separated by an area character.

./most important.swift hiya world

In Xcode you may add customized arguments underneath the Edit Scheme… menu merchandise once you click on on the present scheme, search for the Arguments tab and use the Arguments Handed On Launch part.

Course of data and surroundings in Swift

Similar to we will entry command line arguments, it’s doable to look at the present course of together with some {hardware} data and surroundings variables.

#!/usr/bin/env swift
import Basis

let data = ProcessInfo.processInfo

print("Course of data")
print("Course of identifier:", data.processIdentifier)
print("System uptime:", data.systemUptime)
print("Globally distinctive course of id string:", data.globallyUniqueString)
print("Course of identify:", data.processName)

print("Software program data")
print("Host identify:", data.hostName)
print("OS main model:", data.operatingSystemVersion.majorVersion)
print("OS model string", data.operatingSystemVersionString)

print("{Hardware} data")
print("Energetic processor rely:", data.activeProcessorCount)
print("Bodily reminiscence (bytes)", data.physicalMemory)




The surroundings variables property is a Dictionary the place each the keys and the values can be found as strings, so that you might need to parse them in case you are searching for totally different worth varieties. You may arrange surroundings customized variables in Xcode identical to arguments, or you may move them by way of the command line earlier than you execute the Swift script utilizing the export command.

Customary enter and output in Swift

You should use the print operate to write down textual content to the usual output, however you must observe that the print operate has a variadic gadgets definition, so you may move round a number of arguments and a customized separator & terminator parameter to show extra superior outputs.

There may be additionally an ordinary error stream, which is a part of the customary streams after all, however what’s attention-grabbing about it’s that you could additionally write to this channel via the FileHandle.standardError property there may be fairly a chic answer on a Stack Overflow thread initially created by Rob Napier, I’ll embody that one right here as properly. ?

One other nice function of the print operate is the to parameter, which might settle for a customized TextOutputStream so you may wrap the stderr stream in a customized object or you can too create customized output handlers and separate your print statements e.g. by context for those who want.

#!/usr/bin/env swift
import Basis

print("This", "is", "enjoyable", separator: "-", terminator: "!")

"This goes to the usual error output"
    .knowledge(utilizing: .utf8)

remaining class StandardErrorOutputStream: TextOutputStream {
    func write(_ string: String) {

var outputStream = StandardErrorOutputStream()
print("That is additionally an error", to: &outputStream)

func clear() {
    print("u{1B}[(1);(0)H", terminator: "")

print("Hello, world!")

print("u{1b}[31;1mu{1b}[40;1m("Hello, world!")u{1b}[m")
print("u{1b}[32;1m("Hello, world!")u{1b}[m")

print("Please enter your input:")
guard let input = readLine(strippingNewline: true) else {
    fatalError("Missing input")

The second half of the snippet is full of ANSI escape codes which I like quite a lot, because it can make our terminal output quite beautiful. The only problem is that they don’t work in Xcode at all (come-on Apple, please support this…). You can clear the console or change the background / foreground color of the output by using these codes.

There are quite a lot of libraries on GitHub that you can use to print colorful output, for example ColorizeSwift, ANSITerminal, ANSIEscapeCode and many more cool ones.

The very last thing that I’d like to show you is the readLine function, which you can use to read a line from the standard input. This comes handy if you need to get user input from the command line.

Use an argument parser library

If you are looking for a type-safe argument parser written in Swift, you should definitely take a look at the Swift Argument Parser library. It is created and maintained by Apple, so it’s kind of an official solution for this particular issue, but IMHO it lacks some advanced features.

This is the main reason why I prefer the Vapor command API built on top of the ConsoleKit library. Both libraries can parse arguments, options and flags, but ConsoleKit is also capable of displaying progress indicators, it features multiple command groups, secure input, auto-completion, multiple log levels and many more.

import Foundation
import ConsoleKit

final class HelloCommand: Command {
    struct Signature: CommandSignature {

        @Argument(name: "name", help: "The name to say hello")
        var name: String

        @Option(name: "greeting", short: "g", help: "Greeting used")
        var greeting: String?

        @Flag(name: "capitalize", short: "c", help: "Capitalizes the name")
        var capitalize: Bool

    static var name = "hello"
    let help = "This command will say hello to a given name."

    func run(using context: CommandContext, signature: Signature) throws {
        let greeting = signature.greeting ?? "Hello"
        var name = signature.name
        if signature.capitalize {
            name = name.capitalized
        print("(greeting) (name)!")
        let bar = context.console.progressBar(title: "Hello")
        let foo = context.console.ask("What?")
        let baz = context.console.ask("Secure what?", isSecure: true)
        let c = context.console.choose("Make a choice", from: ["foo", "bar", "baz"])


import Basis
import ConsoleKit

let console: Console = Terminal()
var enter = CommandInput(arguments: CommandLine.arguments)
var context = CommandContext(console: console, enter: enter)

var instructions = Instructions(enableAutocomplete: true)
instructions.use(HelloCommand(), as: HelloCommand.identify, isDefault: false)

do {
    let group = instructions.group(assist: "Utilizing ConsoleKit with out Vapor.")
    strive console.run(group, enter: enter)
catch {

You should use each answer via the Swift Bundle Supervisor, the setup course of is kind of simple, you will discover extra tutorials in regards to the Swift Argument Parser and I feel that it’s more durable to seek out correct docs for ConsoleKit, so yeah… anyway, they’re nice libraries you will not remorse utilizing them. ?

Make the most of the Swift Bundle Supervisor

The Swift Bundle Supervisor is without doubt one of the neatest thing in regards to the Swift programming language. I actually like it and I exploit it virtually on daily basis. The truth that the package deal manifest file is outlined utilizing Swift itself makes it simple to make use of & perceive.

import PackageDescription

let package deal = Bundle(
    identify: "myProject",
    platforms: [
    dependencies: [
        .package(url: "https://github.com/vapor/console-kit", from: "4.1.0"),
    targets: [
        .executableTarget(name: "myProject",dependencies: [
            .product(name: "ConsoleKit", package: "console-kit"),
        .testTarget(identify: "myProjectTests", dependencies: ["myProject"]),

The package deal supervisor advanced quite a bit through the previous few months, for those who check out the Swift Evolution dashboard you may monitor these modifications, the latest replace was the introduction of customized, user-defined Bundle Collections, however in case you are searching for packages you may all the time check out the Swift Bundle Index web site. ?