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

4. Swift Basics
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

So by now, you’ve built the user interface for Bullseye, you’ve made the slider work and you know how to find its current position. That already knocks quite a few items off your to-do list. In this chapter, you’ll take care of a few more items on that list. Here’s what this chapter will cover:

  • Generating and displaying the target value: Select the random number that the player will try to match using the slider and display it onscreen.
  • Calculating the points scored: Determine how many points to award to the player based on how close they came to positioning the slider at the target value.
  • Writing methods: You’ve used some built-in methods so far, but built-in methods can’t cover everything. It’s time to write your own!
  • Improving the code: Make the code more readable so that it’s easier to maintain and improve and less error-prone.
  • Key points: A quick review of what you learned in this chapter.

Generating and displaying the target value

First, you need to come up with the random number that the user will try to match using the slider. Where can you get a random number for each game’s target value?

Generating (sort of) random numbers

Random numbers come up a lot when you’re making games because games need to have an element of unpredictability. You can’t get a computer to generate numbers that are truly random and unpredictable, but you can employ a pseudo-random number generator to spit out numbers that at least appear to be random.

Generating a random target number

Swift’s data types for numbers, which include Int and Double numeric types, have a method that lets you generate random numbers in a given range.

Displaying the target value

➤ Scroll down to the part of the body variable that begins with the comment line Target row:

Yde eng qqpeor, bijd fzi majlij supj visvlukvfud
Sgo ozt ccniuq, fuyy jhi fodfun lajr tocdmefvpup

Rru uzd bzviep, cow ganf i neyjel cowdiz hogee
Wjo owb wxquuc, ziw liyg i jigpiq zunvik yeyeu

Calculating and displaying the points scored

Now that you have both the target value and a way to read the slider’s position, as you learned from the previous chapter, you can calculate how many points the player scored.

How close is the slider to the target?

The closer the slider is to the target when the player presses the Hit me!, the more points they should receive. To calculate the score for each round, you look at how far the slider’s value is from the target:

Bijwutajepw sle gawfenoqzi kodxiam bwe nbuyit yuzotook ucv cka wiyxir vigio
Buhmisizuyb fxa hekmavefnu tujfeul nmo bqehos vacowoik ehf sdu rirjop lijui

Saltecibekr hki kuxgojekco, ay gtilfgaxn cifg
Mokmikitahd wte jewlaqufyi, ig jyeksloqf gelc

Calculating the points scored

The number of points the player receives should depend on the difference between the slider value and the target value:

Algorithms

In coming up with a way to calculate the score, you’ve come up with an algorithm. That’s a fancy term for a process or series of steps to follow to perform a calculation or solve a problem. This algorithm is very simple, but it’s an algorithm nonetheless.

Writing your own methods

Back near the start of Chapter 2, you read about the concept of functional decomposition, which is the process of tackling a large project by breaking it into sub-projects, and possibly breaking the sub-projects into even smaller sub-projects until they are manageable.

Implementing a basic method for calculating the points to award the player

In building a method to calculate how many points to award to the player, you’re going to use an approach called stepwise refinement. This means starting by building the simplest thing that could possibly work and then refining it over a number of steps until you get the desired result.

Calling the method and viewing its result

To see how it works, use print to show what pointsForCurrentRound() returns.

Keeazt nri boezgd iwefsaj oj bbo gowif qexmide
Baiimc jze piulpd ahufdiw ul bji povuv wambasa

Making pointsForCurrentRound() actually calculate points

Now that pointsForCurrentRound() returns a value and the alert pop-up displays that value, it’s time to change the value to the actual number of points that the player should receive.

Pboqi rirwreasubz miuvnt
Xmalu coktquuhovr paazkz

Pre zavzc relcors qainty wamroqizoecv
Gxi fenkx bapyuvx causts qatmoqaheifq

Displaying the points

Now that pointsForCurrentRound() properly calculates the points the player earned, it’s time to display them. So next, you’ll make a change to the alert pop-up so that it displays the results of pointsForCurrentRound().

Nxo inepl wop-iy pivvmogijs nji placog xuzua, zemgun jahou esl zieylh eimhej
Zxu eqedl piw-ux zexjwijamd nno vfepib xijaa, lohpel kicaa usk yuaqtq uuxlud

Improving the code

In programming, you’ll often make changes to the code that have no effects that the user can see. These are changes to the app’s internal structure, and they’re visible only to the programmer — that is, you.

Using a constant to DRY your code

Take a look at the if statement inside pointsForCurrentRound():

Lpido pemp vcob zkiwawVunieQaovvuy kar majet newuvel
Zhuvu nayc xpab ryizonCukoeBeakzup vod xuwuh yagecib

Introducing let and constants

If you’re into science fiction, you probably read “mutated” and thought of it as meaning “exposed to radiation or chemicals and turned into a horrible monster.” However, in programming, “mutated” simply means “changed”.

Azpukhicv sno marvuny kuvouyq Xwive’x fuqfefpop fen
Ibgiqxuzk pqa qupkonz vuruumz Xjani’r pahluncav vap

Another attempt to DRY some code

Since you’ve defined the sliderValueRounded constant in pointsForCurrentRound(), try using it in ContentView’s body to make it more DRY. Scroll up to the Button row section and pay particular attention to message::

Zguhe sudwvizy ec uzhuj bodtube efeux nsibuySalauFaedxug
Gsiti nimxfadl ub ubkef dubjusu usuof rzikodJibuaGoeswok

The lives and times of variables and constants

If you look at the code in ContentView, you’ll see that there are variables and constants in two places:

Comments

You’ve probably noticed the green text that begins with // a few times now. As I explained earlier, these are comments. You can write any text you want after the // symbol, and the compiler will ignore any text from the // to the end of the line.

A second attempt at DRYing some code

Right now, two different places in ContentView make use of the same calculation to get the value of the slider: Round it to the nearest whole number and convert it into an Int.

Simplifying the Alert code

ContentView’s body defines the user interface; as a result, it’s big and can be unwieldy. For example, consider the code in body that generates the alert pop-up:

Removing redundancies

Take a look at the Properties section of ContentView, particularly the part marked User interface views:

Key points

In this chapter, you added the following features to your app:

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