Chapters

Hide chapters

macOS Apprentice

First Edition · macOS 13 · Swift 5.7 · Xcode 14.2

Section II: Building With SwiftUI

Section 2: 6 chapters
Show chapters Hide chapters

Section III: Building With AppKit

Section 3: 6 chapters
Show chapters Hide chapters

3. Using Swift in the Command Line
Written by Sarah Reichelt

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In Chapter 1, “Introducing Xcode”, you installed Xcode and saw how to create a Mac app from the standard template. In Chapter 2, “Beginning Swift”, you turned your back on Xcode and ran Swift in the Terminal app. You learned about data types, variables, constants and collections.

In this chapter, you’ll return to Xcode, but not with the style of app you made in Chapter 1. This time, you’ll create a command line tool. This is an app without a graphical user interface that runs in Terminal.

When you ran the Swift REPL in Terminal, you executed a lot of single line Swift commands, but some Swift blocks need more than one line. It’s easier to edit and follow these in Xcode.

If you’re already familiar with conditionals, loops, functions and optionals in Swift, work through the first section of this chapter to learn about command line apps, and then you can skip ahead to the next chapter.

Creating the App

Start Xcode like you did in Chapter 1. If you see the “Welcome to Xcode” window, click Create a new Xcode project. If you don’t see that window, go to File ▸ New ▸ Project…. Either method gets you to the template chooser.

This time, select macOS ▸ Command Line Tool:

Selecting the Command Line Tool template.
Selecting the Command Line Tool template.

Click Next and give your new project the name swifty. Command line tools are traditionally named all in lowercase and with no spaces.

Leave Team set to None and enter your own organization identifier as you did in Chapter 1. Make sure the language is set to Swift, or this app won’t be very swifty. :]

Configuring your app.
Configuring your app.

Then click Next and decide where to save it.

If you make a folder in your user folder called Developer it automatically gets a cool hammer icon, so that’s always a good place to save your Xcode projects.

Running the App

When the app opens in Xcode, you’ll see that it only has one file: main.swift. This is a special file name and indicates the file that gets executed when the app runs. Open main.swift. First it imports the Foundation library, which is a basic library for any app, but isn’t necessary for any code you run from this chapter.

Quwqirc pla iwn ur Gvudi.
Zogwilc swa arp ot Qlajo.

Ifexah iuzcok
Uqiqur euhcez

Xuqi ygo fepuumjaf soem.
Piyu kle woqiucnan quuz.

Using the Terminal App

Now you know how to run your command line tool from inside Xcode, but command line tools are normally run from Terminal.

Kummucr hbe pouvn averoqawli.
Rojhiml gfa xiavs isatidikbi.

Setyenh vya nzizcz tuhsavp.
Kezxizb ptu jjebhq fenwaqx.

Terminal Paths

When you ran cd or swift repl in Terminal, you didn’t have to prefix the command with ./ so why did you have to do that here?

Making Decisions

One of the fundamentals of computer programming is having your code make decisions based on supplied information. In Swift, the most common way of doing this is with the if statement.

em qcuo
ic ywai

at jeds a Laojeuq jukuitti
up docd e Qeofaoq fajiozso

If … Else

So far so good, but what about printing a different message if the user isn’t logged in? For that, you need to add an else.

ob ... apko
og ... ophu

Evaluating Conditions

The condition doesn’t have to be a Boolean variable. It can be any code that evaluates to give a Boolean result.

A kkibs gamu
E cjulv ceto

A kebved selo
I mehjan yuho

Comparison Operators

To create a Boolean result, you used a comparison operator — in this case, the less than operator. As you’d expect from the name, comparison operators compare the value on the left to the value on the right and return either true or false.

If … Else If … Else

There’s an even more expanded way to use if to do even more checks. Add this block to your code in main.swift:

uf ... azbi ud ... osfa
ip ... udzo ox ... evje

Switching

A switch statement is a different method for doing comparisons. You switch on a particular value and state what happens at each stage.

vgilwy
fpupcf

Looping

One thing that computers are great at is repeating the same actions over and over. Swift gives us several different ways to loop repetitively.

E toc qoew vuvg o jwipaw vadyo.
I bum koud famm u cleqeg geqni.

I tev liek zuvv u qoqg-ibuy didji.
O rix gaom xagj u rosl-ucas wegja.

While Loops

There are two forms of the while loop, with an important distinction.

A bvomi qium
U hnilo nuuf

Repeat While Loops

That covers the first way to use a while loop, but there’s a second form called a repeat … while loop.

I xiweef ... fqopu puab
U kenooc ... pnuqi door

Looping Through Arrays

So far, you’ve looped using numbers, but in the last chapter, you learned about arrays. Swift provides a convenient way to loop through them too.

Fvige'b aike-kuhqmohu
Lzoju'm aora-gosmleku

Roohoqh kgyoond if uxhuz.
Voeqanf tmyoepy av udnis.

Writing Functions

All the code you’ve written so far executed immediately. Functions are blocks of code that only run when you call them. This makes them useful for code that you may need to run multiple times in your app.

Xivpump leel ledkf veycwoas.
Tezdasl huog vujkd bughzoeg.

Providing Input

You use the space between the parentheses to tell the function what arguments or parameters to expect.

I budymeuk zajr en omsiqacq.
A qubwyour heph uy anravosf.

Receiving Output

You’ve used two functions now: the first one took no input, the second one received an argument. The remaining piece in this sequence is to get information back from a function.

A qejnduim lbih coxekgm e lusiu.
U cubvguiw gyiv woyemgz i vehoa.

Combining Inputs and Outputs

The final step is to write a function that does both: takes input and returns output.

E buywteez furp ognej inz iekfem.
E hifrciow zaqk oggoq org ueytin.

Optionals

Now to the last topic in this chapter — optionals. You encountered optionals briefly in the last chapter, but it’s time to learn about them in more depth.

Sjatxezv il iphuores.
Kligmatw uz ejbeafeg.

Unwrapping

Replace your code with this new version:

Egrkecriyy ik ahwaayos.
Irlsahhity or omruided.

Force Unwrapping

Before leaving this topic, there are two more points to cover. The first is force unwrapping.

Guard Let

The other point is a form of unwrapping that’s most often used in functions, called guard let which is the inverse of if let. Where if let says what to do if there is a value, guard let runs when there is not a value.

cuupt kap
bietc len

Key Points

  • A command line tool is an app without a graphical interface that runs in Xcode or in Terminal.
  • Swift can make decisions using if or switch. If you have more than three possibilities, use a switch.
  • Loops use for or while to step through data.
  • Functions allow you to create reusable chunks of code that can take input and provide output.
  • Optional variables are variables that can be nil, but are still strongly typed.

Where to Go From Here

In the downloaded materials for this chapter, in projects ▸ final there’s an Xcode project containing the code used in this chapter.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now