Your First iOS & SwiftUI App: An App from Scratch

Jan 11 2022 · Swift 5.5, iOS 15, Xcode 13

Part 3: Coding in Swift

27. Variables & Constants

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 26. Challenge: Calculate the Difference Next episode: 28. Type Inference
Transcript: 27. Variables & Constants

At this point, you’ve simplified your algorithm to calculate the difference down to 3 lines of code.

That’s good, but we can do even better; we can get it down to one line of code!

In this excercise, we’ll finialize our revisions to the difference algorithm, and put it all together to calculate the score and display it to the user. Along the way, you’ll learn about an important Swift concept: the difference between variables and constants.

Let’s dive in!

Help\Developer Documentation. Swift Standard Libary\Int. Halfway down, find section “Finding the Sign and Magnitude”. Abs function.


var difference: Int = abs( - sliderValue)

Explain we’ve been getting warnings, they say ‘consider changing to let constant’, and you might be wondering why that is. That leads me to an imporant discussion, about the let vs. var.

It turns out Swift makes a distinction between variables and constants.

As we discussed in the episode on Variables, you can change the value of a variable at any time. However, once you set a constant, you can never change it again. If you try to change it, the Swift compiler will give you an error.

The keyword var creates a variable, while let creates a constant.

In the first versions of your algorithm, you declared the difference as a variable, because the value could change depending on you if/else statement. But in the latest version, once you calculate the difference, or the awardedPoints, they will never change again. So they could really be a let - or a constant, rather than a variable.

When you declare a value that will never change in Swift, it’s better to make it a constant with let. This makes your intent clear, which in turn helps the Swift compiler understand your program better.

A good rule of thumb is prefer to use constants with let as much as possible, and only use variables with var if you need to change the value later on. That way, the Swift compiler can optimize your code as much as possible.

That’s why we’ve been seeing these warnings in Bulleye so far. It’s because Xcode noticed that in some cases, we have been using var to declare variables, but those variables never changed, so we could have used let - and it helpfully notified us about that.

So let’s go through and update those variables to constants, which should resolve all our warnings and get Bullseye in a clean state.

Game.swift; Lines 16+

let difference: Int = abs( - sliderValue)
let awardedPoints: Int = 100 - difference

ContentView.swift; Line 67

let roundedValue: Int = Int(self.sliderValue.rounded())

Unit tests