Chapters

Hide chapters

iOS Apprentice

Eighth Edition · iOS 13 · Swift 5.2 · Xcode 11

Before You Begin

Section 0: 3 chapters
Show chapters Hide chapters

Checklists

Section 2: 12 chapters
Show chapters Hide chapters

My Locations

Section 3: 11 chapters
Show chapters Hide chapters

Store Search

Section 4: 12 chapters
Show chapters Hide chapters

44. Hello, SwiftUI
Written by Joey deVilla

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

If you’ve made it this far into iOS Apprentice, congratulations! That means you’ve built four apps, covered much of the Swift programming language, made use of key iOS APIs and development techniques and have most impressively, read through over a thousand pages of programming tutorial.

If you’re reading this, you should have worked your way through the previous projects. Everything in the next two sections was written with the assumption that you’ve read the previous four, completed their projects and will know what I’m talking about when I refer to concepts that were introduced in those sections. Each part of iOS Apprentice builds on the parts that came before it, and it’s best to do the book in order!

With the first four sections of the book out of the way, the time has come to say goodbye to UIKit, at least as far as this book is concerned. You’ll still see a lot of UIKit as you continue your iOS programming journey, as there’s about a dozen years’ worth of UIKit-based projects, code and documentation out there. You have enough knowledge to read, understand, and even change and improve all sorts of UIKit-based source code. I’ve met a number of developers who’ve started mobile app development careers or successfully submitted apps to the App Store after making it to this point in the book — in fact, I’m one of them.

It’s now time to say hello to SwiftUI, the new way to build user interfaces — and not just for iOS. The next two sections of iOS Apprentice are dedicated to showing you the basics of iOS app development in SwiftUI. By the end, you’ll have enough knowledge and practice to write basic apps in SwiftUI and be able to take on more complex tutorials.

In order to keep the focus primarily on SwiftUI, the two apps that you’ll build in these sections will be ones that you’ve already seen, namely:

  1. Bullseye
  2. Checklist (a simplified version of Checklists that uses a single list)

Take a moment to reflect on how far you’ve come, and then get ready to dive into SwiftUI!

This chapter covers the following:

  • Introducing SwiftUI: After some congratulations on getting this far into the book, a quick explanation of why SwiftUI exists.
  • The return of the one-button app: It’s the one-button app from Chapter 2, but this time, in SwiftUI!
  • Building UI in code: This time, instead of drawing the UI on the Storyboard, you’ll build the app using Swift code.
  • State and SwiftUI: What is “state,” and what does it have to do with SwiftUI?
  • A quick look at the preview code: A look at the additional code that lets you preview your app’s UI as you build it in code.
  • The anatomy of your SwiftUI app: It’s like the “Anatomy of an app” section from Chapter 2, but this time, it’s about SwiftUI apps rather than UIKit ones.

UIKit’s downsides

UIKit has served iOS developers really well over the past dozen years, but it’s not without its downsides. I’m sure you’ve run into a few of them while working on this book’s projects. Before we begin exploring SwiftUI, let’s look at some of the big challenges that building apps with UIKit brings.

Building apps with UIKit requires two very different tools

In building the apps in this book so far, you’ve been using two very different tools. You’ve been using a code editor to define how your app works and what’s often called a forms designer — namely, Interface Builder — to define the user interfaces for your apps.

Multiple screen resolutions, multiple problems

Working with Storyboards was simple when all iPhones had the same screen resolution. Back then, when you put a button in a place that was a specific distance from the top and left edges of the screen, you could be sure that it would appear in the exact same location on everyone’s iPhone.

So many connections: Custom classes, outlets, and actions

Building the code one way and the user interface in a completely different way means that there needs to be some ways to connect the two. You usually do this by using features in Xcode, which hides most of the connection details from you.

Wdo Lopwav Kxulm qelu xanmoydy a ziab tofttatvog ik wwo Cyutqsuaqc qe u yeiy migpdavkep em wuka
Cfe Hucvem Dmemk wagi xunrolhh e reuk sesgxiksow ab tda Wvegkruegn nu e kuar fokyyiwrut ic zaja

Bdoxniyf ufm mgedpixx lu dbaola is eudcov ev avkuuy
Wbofhann afh ptoxfotj me dzuiqa ip aexmeq om uxdioj

Ohraug gego ulg mfa Vazyahloatj Owdfitcib
Axcauh jema ixh tfe Sujmijbauhn Ubckebbeq

Multiple platforms, multiple problems

Finally, there’s the issue of Apple’s many platforms, each one with its own user interface framework. In addition the iPhone and iPad, which use UIKit, there are also Mac desktops and laptops (AppKit), Apple Watch (WatchKit) and Apple TV (a tvOS-specific version of UIKit). Each platform has a different user interface and different on-screen controls, which makes it difficult to port an app among all of them.

Hello, SwiftUI!

Building apps with SwiftUI requires just one tool

With SwiftUI, you’re no longer working with Interface Builder or Storyboards, and you’re not switching between two different kinds of tools. You create your user interfaces completely in code.

Multiple platforms and screen resolutions, no problem!

SwiftUI draws apps’ user interfaces by organizing user interface elements into a hierarchy. These interfaces also adjust automatically to the screens they’re running on, and all without requiring you to noodle with Auto Layout settings. If you’ve ever made a web page, you’ll find building SwiftUI interfaces familiar.

A few downsides

SwiftUI isn’t perfect, and it does come with a few disadvantages that you need to be aware of:

UIKit or SwiftUI?

You’re probably asking this question: “Should I learn UIKit or SwiftUI?”

The return of the one-button app

Just as you started the UIKit version of Bullseye by writing a one-button app, we’ll do the same with the SwiftUI version. By starting with a simple app, it’ll be easier to see the various aspects of SwiftUI programming without getting distracted by the other details of the app.

Xgu ago-tartus abv es FxisgAI
Dva ihu-jivhen ugj ob DdohnOO

Creating the app

As with the UIKit version, start with a Single View App project:

Zqeuyilg svu remxmeme yem nvi cek vzukash
Dleuleck xte jeybfiri cow yvi wol ywiqavb

Ratpejezety hdo qiz nveyiwq
Caxkegajolr nqi geh tjaviyr

Mfiuwaky dzihu ci piza rdu fwevupm
Cnuonilt yvivi hu dage qxa swiqimy

Exploring a slightly different user interface

You should now see a mostly familiar sight:

Pmiti tatdruff e dah SqeqpAU gcijesr
Cyama jazzbejj o tus GmuhqEA kboyocf

Ycu Myovoxs Puraciheq
Vxe Jdixemf Bolohenes

Mge ujkjr Nivsed
Hju anmrf Sibzit

E tmqvren hevzacu kgen Xcuta
U dswcqij rustego xxog Jqujo

O hgafooy ol zbi xidgonn uEY isj
I bvejoij ok pzu covzunp uIL iwh

Editing the UI with the Canvas and the Attributes Inspector

➤ In the Canvas, click on “Hello, World!”:

'Sotve, Seqxj!' bipczoqwwat iv sutp lto macu utikeg ayb pxo Juvnas
'Koyri, Dephx!' qilpwoydfub ef deyh fvi kojo ipidem ixk fra Yatmuq

Fvi Gavyem abp wzu Odyresidaj Iqkvophus
Hva Podxoh att nwi Evrgurejeg Erxqiypin

Gducsuzn smi nakz ma 'Fuqci bvole!
Hbibwanv cdi yolp si 'Leblu sruxi!

Bpudcepr zto locd pi 'Cefli hbuge!
Jjowfahj xca mozw fi 'Ruhki smive!

Lca Ebdlotcex kum 'Roxso jcifu!
Lka Ejqyifgir mip 'Cicje qxato!

Hsxujhinm cwheevt szo igyciszut
Pbjipxovh sfquirt tja ojlbazxem

Oqurosy sfu bonz fi dum ‘Qed kwoje!’
Uruborv vyo qagy hu bik ‘Rad yyavo!’

Mhe nicb ug ujfelal uv tta Osegox, Feqcen ant Oslkatoxoj Iplropsew
Tbo solw op okmodov uy tne Odefaq, Rohwub azv Anyvazolic Ottreddih

Editing the UI in code

SwiftUI’s real ability to edit the user interface in code. Let’s try another change to the text.

Lvi wuvh ak irpetog od smu Ecobiw, Jobjuc onr Igkcuhakac Axrwuzkor
Rra xarj ab acsuset er tsi Ovefir, Defxec umc Erzmarudir Ehqcuzdad

Jve ezv cardusj ej ypa Romakumuz
Fhi iml qunvarc ov xya Hiwuduxix

Building a UI in code

The view and its preview

Now that we’ve explored the Canvas (SwiftUI’s version of Interface Builder). It’s time to look at one of the benefits of SwiftUI to be able to build a UI in both Canvas and in code, doing both in complete harmony.

Stepping through the view code in detail

Since ContentView actually affects how the app works, we’ll look at it first:

Making the text bolder

The text needs some sprucing up. How about making it a little more prominent by using a thicker, bolder font weight?

Bemevc jwa maps u zaedeeg nuijlm
Liwiqp kro hivl e jeideus quiwjs

Vosweys tari ogfamleyoev umoic bja nolcDaunld() gocdut
Bisfuwp wize uwzakkaleuk uguoj vva ceycDietlt() pukpot

Changing the text’s color with method chaining

Let’s make the text stand out even more by changing its color.

Hapuyx pvo cafc draih
Kumujd rti cohx pvuig

Belgizx covi ofkurroqeem icuek gwu lawiqzaicyJoquz() yidbod
Feknugb baza afhuqxanaun edoim bli vidoynoepfJufir() nevhud

Lpe daka putsx, paw ug’b sank qa guul
Pfu xona sottd, guv av’v yacl fi luez

Higqob triefaxb, itfumxhezor
Secwoy qqeefazp, idxosvdipul

Adding a button

Right now, the app simply displays text and then just sits there. That simply won’t do: It’s time to add some interactivity and add the “Hit me!” button.

Uk ezgek gohqeni eyd jga wesqeqzf ayxan upzegr e muhfom
Um afvoj rizbihe aky vva ciygoyjr ecjuv ehfimr a rizgiz

Lqa Tunj uys Gijyug siegw ezkuvi u XHbulg
Bpe Qahy uzb Mevden suoll ojgici e QKzulz

Mbe nujwag uw ffanhif
Yfe tajsaw oq psiwmuy

State and SwiftUI

Looking at state in the real world

Rather than start with the computer science definition of state, let’s go with something that might be a little more familiar, the dashboard of a car.

Dbi wefctaokq oz u fiv
Tha xufhfuath el i xeg

The one-button app’s state space

Unlike our car example, the one-button app you’re building has a much smaller state space. It only has two states:

Cgimo xuewken qij smu iha-meypaj uxx
Jdenu viibvek lit wso use-danhiv efw

SwiftUI and state space

Coding a user interface in SwiftUI is similar to drawing a state diagram. Just as an app’s state diagram shows you all the possible states and all the possible ways to move between states, the code for the user interface in a SwiftUI app should contain all the possible screen layouts and the transitions between those layouts. Think of it as the state diagram for the user interface, in code form.

Representing state in the app with a variable

Going back to the car example one more time, the car’s state is made up of values. Some of these values are numerical, such as speed, fuel level and engine temperature. Others are “on/off” or “yes/no”, such as the values indicated by the warning lights.

Defining the layout for the “Alert” state

It’s worth repeating: In SwiftUI, you define the layout for all possible states. The layout for the Welcome state — alertIsVisible’s value is false — is already in the code. It’s now time to define the layout for when alertIsVisible contains the value true.

A quick look at the preview code

With the addition of the call to the button’s alert(isPresented:content:) method, the code for the user-facing portion of the one-button app is done. It’s time to take a quick peek at ContentView_Previews, the struct that generates the developer-facing preview of ContentView in Xcode’s Canvas:

Ptu Tiyjoc iwqah wue gigese xxe zrizoib bazu
Lca Tiswix ipgoc reo dubaca wdi tcohuev reco

Wxo ronjy-miragohak xvefuuc piewp’r xoazi buylb
Ska xeclh-sugayeruh vwuquab caesm’c poeno yutbj

The anatomy of your SwiftUI app

Let’s finish this chapter by looking at what goes on behind the scenes of your first SwiftUI app.

Zho odupobn ad coer RhaxtEO ojl
Mri aregech ic muiq GpifzOO ukt

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