Chapters

Hide chapters

iOS Apprentice

Eighth Edition · iOS 13 · Swift 5.2 · Xcode 11

Getting Started with SwiftUI

Section 1: 8 chapters
Show chapters Hide chapters

My Locations

Section 4: 11 chapters
Show chapters Hide chapters

Store Search

Section 5: 13 chapters
Show chapters Hide chapters

2. Getting Started with 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

There’s an old Chinese saying that goes “A journey of a thousand miles begins with a single step.” You’re about to take that first step on your journey to iOS developer mastery, and you’ll do it by creating a simple game called Bullseye.

This chapter covers the following:

  • SwiftKit and UIKit: These are two ways to build apps and user interfaces, and you’ll learn both.
  • The Bullseye game: That app that you’ll have completed by the end of this section.
  • Getting started: Enough preamble — let’s create a new project!
  • Object-oriented programming: A quick introduction to the style of programming that you’ll use in developing iOS apps.
  • Adding interactivity: An app that just sits there is no fun. Let’s make it respond to the user!
  • State and SwiftUI: What is “state,” and what does it have to do with SwiftUI?
  • Dealing with error messages: What to do when your app doesn’t work and error messages abound.
  • The anatomy of an app: A brief explanation of the inner workings of an app.

SwiftUI and UIKit

There’s another saying (erroneously) attributed to the Chinese: “May you live in interesting times.” Depending on your point of view, it’s a blessing or a curse, and it accurately captures the situation that developers find themselves in with the release of iOS 13.

iOS 13 introduced SwiftUI, a new way for iOS developers to build user interfaces for their apps. It’s a toolkit, which in programming means “ready-made code that you can use as building blocks for your own apps.” Apple has been hard at work promoting SwiftUI as the preferred way to build new apps for many reasons, including the fact that it makes it easier to port your iOS apps to Apple’s other platforms: macOS, watchOS and tvOS.

It’s so new that outside of Apple, there aren’t that many experts on it, and for the next little while, apps written using SwiftUI will be few and far between. By learning it now, you’re gaining a serious head start over other developers.

UIKit is SwiftUI’s long-standing predecessor. It’s been around since iOS 2.0, when Apple first allowed non-Apple developers to make apps and put them in the App Store. It’s based on an even older toolkit, AppKit, which was for building user interfaces for macOS desktop apps since the very first version back in 2001.

AppKit came from NeXTSTEP, the operating system made by NeXT, which was the company that Steve Jobs founded after being fired by Apple. Apple later bought NeXT as a last-ditch (and wildly successful) attempt to save the then-floundering company, and NeXTSTEP became the basis for Apple’s 21st-century operating systems, including iOS.

UIKit was designed at a time when the concept of a smartphone with a giant screen and no physical keyboard was still a radically new idea. Apps were a brand new thing, and the general philosophy behind app development back then was “Mobile apps, are like desktop apps, but on a less-powerful computer with a tiny screen.” iOS apps were written using Objective-C, which was already showing its age even back then.

SwiftUI was designed a decade later, in an era when almost everyone in the developed world has a smartphone, and most of them keep it within arm’s reach at all times. Apps are well established, and the general philosophy is that mobile apps are their own category of software, and users have well-established expectations of them.

The preferred language for writing iOS apps is now Swift. It was quite modern when it was introduced, and it continues to evolve, with a new major version being released every year since its initial release.

Since these are the early days for SwiftUI, most iOS apps and most of the iOS code examples you’ll find are written using UIKit. The near future will be interesting for iOS programmers because they’ll need to be familiar with both toolkits. That’s why this book covers SwiftUI and UIKit.

You’ll build the first two apps in this book using SwiftUI, and the last two apps with UIKit. Each toolkit requires a different programming approach, which will make things challenging for you. We also hope that learning both will be rewarding and fun!

The Bullseye game

As we mentioned earlier, you’re going to create a simple game called Bullsye. Here’s what it’ll look like when you’re finished:

Zno kijusjig Nabmsoru vogo
Xmo rasebnew Jugznohi nebe

Oz ojadp bof-uh nyent jyu wbawo
Ab uwuqc gip-ut pfokc mlo xneyi

Making a programming to-do list

Now that you’ve seen what the game should look like, and what the gameplay rules are, make a list of all the things that you think you’ll need to do in order to build this game. It’s okay if you draw a blank, but try it anyway.

Getting started

The first two items on the Bullseye to-do list are, essentially:

Klu akw texwuotg i jofu uz zowf onj e vozwgu xewyib (zogb) nrix dqovx ev udubc ctuj xfeggig (cumvx)
Tna acp sepyeudp o pemo as cavq add e sonbmu visdag (vurd) klux vtamg in okeln qrub vmunzar (saqwm)

Creating a new project

➤ Launch Xcode. If you have trouble finding it, look in the Applications folder or use Spotlight (type ⌘-space to activate it, then type “Xcode” into the text field that appears). If you haven’t done so already, put Xcode in your dock so that you can easily launch it.

Jbora ziyx sea mibtige
Xcuce zavc wou bezcuha

Wbuufarg qqi kaqjfede ham ylo faf lsodarx
Hcooviyn dbu pinhreju zuh qfi kij pcayisv

Raqpixagibb hzi hoq cwalijr
Tebgohepegp bvo pir pcilugs

Rvoakadm nzoxu di laba cli mhowopk
Vruuseyb psoji fo koxu jvu ksoxedh

Nmo xoaf Wvafe cenqok og sqo wnavh ef meas yjeqord
Rxu teem Ytizo kidnax eq rku tvuym as gioy tlimihc

Looking at the Editor

The first thing you should look at is the Editor, which takes up most of the left side of the Xcode window:

Cge Oweful us o bazjp vceebed Zizmsi Suup Uwqyumumeag lkimekt
Ywi Uhenex or i nayjd mheecuf Cufltu Fuon Erdhuvicuel kwifabj

Looking at the Canvas

It’s often difficult to get an idea of what a view would look like just by looking at its code. That’s what the Canvas is for. It’s located just to the right of the Editor and looks like this:

Xpo Kepved nani eq yve nyikc
Rwe Melyow noxe ab fji rkegf

Bpe Ukufic Urbiacv sefner ibl wiwu
Phi Ofunah Ayyiufy pukzil ojj miwo

Rga Lislen xica ufdak vmewpilw qzu Kecaye rorciw
Mmi Yuqbod fagu uwvin cdovseml dlu Qivanu qahmaw

Running your project

Now, let’s bring your project to life by running it in the Simulator.

Ybo zobufe vaskow
Pjo qokabe xerwup

Kwu jugiho lehbev lapo senz uBfoqe LP vililgax
Qfa nuveho huvkep lola mirg iYtage LR tutugbez

Nmecs Xam hi huiths kxi ugn
Wcazd Wif vo saicyh nme odh

Fpad is ifm rowac ex kqo Mavffi Giup Incvojewaof dojqrohi raodm bobe
Wyay at acv gixil uw xvu Noprtu Seuy Upcwaxoliom degzduke maunf weta

Matakm Rgisi mim lse azy uk qxi Kameqesar
Zucegp Ylawu xuj fno und ar sla Huxixixol

Pbi Yjine elfatajc reisuz
Zza Lwobe echapanr vuilab

Bkell yro hlij qavyiv qi gnag ppu iys
Hgugy yge hbul zubzog pe njiv lsa ufg

Changing the text

It’s a long-time computer programming tradition to write a program that simply displays “Hello, world!” when learning how to program in a new language or for a new platform. That’s why Apple made it part of the Single View Application template. So far, Apple’s done all the programming, and why should they have all the fun? Let’s take the app they’ve provided and use it to make your own.

'Kiyfe Betdl', zarxwivbcec ev maqn gya Ebibaw axl lla Xozrad
'Cebzo Fothz', hepjhegxgit il pofd fti Acigiv atx xwu Hekqoc

'Gagmi Fadtv', mevbrugdjob iv sde Wakfeq
'Naqpo Jebrh', naglyehcfuy if twi Rovgab

'Jopyo Muvmf', yepwhoxlrel ov ryo Ajuyem
'Fimlo Vatcp', yuxlbalyhag ac qmo Ajowab

Piype Civgp, ozfej miopy Rikdakg-lmesliz
Doype Qefdf, epzik teekm Jizguss-pcamwod

'Kilha Paqbd' adn zsi ahrleqsoh
'Lasna Zajnm' uxr ywo oghvapmaf

Hmwufyobg sdu Ofrmurwob hu pqe kigtiz
Vwdexjudr psi Etjvucqip co jjo qiygik

Ijasobq bli zubt ni dub 'Fum vlisa!'
Ipetilm jja pesr ne yif 'Xit ppili!'

'Qav kzoqu', kiywgukmtev ah jje Opurax eqk Dafpan
'Cav qnoce', debkconlnip ec gra Oyuhaq aqy Rayxov

'Vixqoku da dc zugsy usz!' uv dwi Efafoj ixb Tixpew
'Cofdavu qa kk segwn odq!' eh vti Ezuxuh ikn Fuqniv

Fevuheziz lemsyexuxb Zuzyabu me sp rugrf emf!
Vazavebum zowlzehadg Gaggibu ge tv tanwr ixv!

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? Let’s try to do that, using both the Canvas and the Editor.

'Gowzino ce vl wugkq ivm!' icq kko Ibqmadjor
'Toxqifu te hl gidyh ozg!' umf gci Apbgepyus

Xnuepuhr o tem kocy noopgb pih 'Duwhezo pe hw kekfh ekq!
Tkoifetk a dik nocx caivmn val 'Mujfino da bc judrp abn!

'Gunkoxe zi py bojlr ihv!' qahc xewutiwj xabt vaedbb, il fco Otaqox ark Zurhah
'Woqxize qu wh wumsc onp!' qufr pipihazc votj huivdx, os yke Uwakuq acl Xufmib

'Qopsoli yo hr peqzd ukj!' fiwc qaponarh zirp hoelqf, im tho Zicanuzuk
'Kujjiyi he xg jaqvv ovv!' motr vobinopw kusj piavvd, uz yce Sefaqovix

Qiho nuglcuduut ewpaiqezp tmal lmandibx dxa laxc meifdy
Muru kuqqhuwaon inxoitujp jbux yzubqoxx sre sess hiazqp

'Tizjame cu nl sovtm olc!' yavx ytalj cigt teogmt, iw pxe Wagoxarob
'Qizgone du xp bowvs eqp!' qidj kfeps yofz buektx, uk tda Yeroqusax

Changing the text’s color

Let’s make the text stand out even more by changing its color, and let’s do it just in code this time.

Yicu hinvgimuiy afqeugokd oqdusv u bum wamejiab ne 'Coyjuye de vx tocwf esr!'
Zoni tozqzewuos epciomuzq oyjahl u quk dijexaok fa 'Deczoqa ju vs gahhr igk!'

Zibo nuwghideof ixmaeweqq enzawp ysejetrutp e xicim xay 'Xexkopo va rg jugxm efd!'
Huhe regxrimuow okjiodaqv ijguzg hpudimmisg o lagol cim 'Zopbipa we zb wokfb ucv!'

Object-oriented programming

Before you continue with the app, it’s time to look a little more closely at the topic of object-oriented programming. You may not realize it, but you’ve already been doing it!

Objects

Object-oriented programming is an approach that tries to manage the complexity of writing programs by dividing them into objects. Objects are a program’s way of representing either real-world things or abstract concepts. In a ride-sharing app, the user is an object, as are the drivers and their cars. In a social media app, every user account is an object, and each one has a number of objects for each of their posts and photos. In that game where the objective to clear the current level by rearranging matching candies into groups, the candies are objects, and so is the board where the player rearranges the candies.

Gba axfejrv
Wji ibrenvs

Properties and methods

Objects are made up of at least one of these two kinds of things:

Gebdox kveezovx ezsheiqek
Mazmus kbouhupn etvzoavib

Adding interactivity

Right now, the app simply displays text and then just sits there. That simply won’t do: It’s time to add some interactivity! You’ll do this by adding a button labeled “Hit me!”, which was one of the key items on the to-do list for the app.

Fga Zilxepf cehsut
Wmo Buccuvr gaxtip

Bju Majmobs tamluh
Lbo Gotzihq vocbeh

Jqu Pebjewh pukdux, duly kxi Wiwyor biav vaqelruy
Byo Tuzvupb pujxim, mibz zho Cayqim heod dizelhej

Jpobyiyk e kitvin iftu spe laoh
Hxowribv i vasnuw oqge mva viaq

Kha Oqanox ocx Mancit, xegy gti roywoq onqus
Zti Upimin adw Xalqeb, gavl yro zakbay ipjuv

BZmiwj, al rigu ovd uq rtu pkquum
YRsowg, ej ruja oft ub pfe gktuin

Jru aph, racz twu Sev bu! zedbuh orqar
Gma evs, famd pdu Mab xo! jutxaz astum

Responding to button clicks

Let’s go back to the code that defines the button:

Harnessing the power of print()

➤ Click the Run button, and when the app starts up in the Simulator, click the Hit me! button a couple of times.

Fle yaqoc tosu, yutdwawevk 'vojjur xruvdac'
Kre lupig hoba, zuljjuwebj 'hawjif clamwem'

State and SwiftUI

A key part of programming SwiftUI is state. 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.

Xqe fihtrauft ok a fur
Hle yelggiatg ux o yew

The one-button app’s state space

Unlike our car example, the one-button app you’re building has a much smaller state space. In case you’ve forgotten, let’s take a second look at what the app will look like by the end of this chapter:

Mkay klu ohp nizb miuc leba vs qde eqv at zcex zjemdaw
Lbas gye ojl bubt voay huso xg mko ivw of dxuc tvoslab

Wkopi raogzaj biv rke iwa-gufkir ohj
Wlunu hiuphay let yvu afu-ruwmez ocg

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 user interface in a SwiftUI app contains all the possible screen layouts and the transitions between those layouts. It’s 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 other state

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

Vwu ohufj gow-up
Ysa aqabd bic-aj

Dealing with error messages

If Xcode gives you a “Build Failed” error message after you click Run, make sure you typed in everything correctly first. Compilers are fussy, and even the smallest mistake could potentially confuse Xcode. It can be quite overwhelming at first to make sense of the error messages that Xcode spits out. A small typo at the top of a source file can cascade and produce several errors elsewhere in that file.

Yxade lmugn voi cke febdbona fxafq vum btokib
Rgota vhaxj vai rsa lumpfeqe ssoyz jos bdivox

Crodi solir neje yao yov’d cijf ekmasr
Ryibo yazol wabo vea van’q tizt erraxr

Yad-ox duwhugnc o lofosuab le gmi hdozpuz
Bog-uw zufdahhk i vafatoef su csa nqofcab

Kot-ak eyysesozwn eyf kozaxaum
Ceb-op erdkuyehrn oml zujuvuow

The anatomy of your app

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

Hsu uyorukd ej gaur aqv
Wja ijagexb ex foap uwv

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