Your First iOS & SwiftUI App: An App from Scratch

Feb 13 2023 · Swift 5.7, iOS 16, Xcode 14

Part 3: Coding in Swift

27. Variables & Constants

Episode complete

Play next episode

Next
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

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 27. Variables & Constants

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

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

Currently, we have added some code to convert a negative number to a positive number. Basically, no matter what we wanna make sure this is a positive number.

Well, this is kind of a common thing that you need to do in your apps, so when there’s a common thing, that’s math related especially like this, it’s a good idea to check the Swift Standard Library to see if there might be a function that can help you.

We could dig around in the developer documentation again to find the parts about Int, or we can let Xcode help us out! Hold option and hover or any of these “Int”s, then click once you see a question mark. Then you can open the documentation for Int directly with the link at the bottom.

Okay, so we can kind of scroll through here to see if there’s any kind handy methods on Int that might help us.

So, we’ve already seen some of these converting floating point values.

We’ve seen creating random integers here’s things to see if it’s a multiple of another number magnitude of a number.

Wait a minute. Here’s one that says return the absolute value of a given number.

So if I click on that, you might’ve learned this from math class.

Absolute value is a fancy way of saying if it’s a positive number it’ll return a positive number. If it’s a negative number multiply by negative one. So this is basically exactly what we’re doing in our algorithm.

So, we can just use this existing function instead of writing it all out ourselves!

Back in our code, just type in abs and parenthesis. You put in whatever the value is and returns the absolute value of that. And then we can delete our other if/else code here.

var difference: Int = abs(target - sliderValue)

Now go ahead and run the tests with Command-U again…

Green checkmarks is great! But next to this in the issue navigator…

Alright, so like we’ve seen a couple of the times in this course. We’re getting a warning on this line. And this warning we can click on it, it says the variable difference was never mutated, consider changing to a let constant, replace var with let.

And now it’s finally time to talk about why this warning is happening. And it leads me to an important discussion about let versus 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 before the method finishes. 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.

So back in game dot Swift, we have this variable difference which is never gonna change once we set it to an initial value. So we can just change that to a constant instead of a variable since we don’t need it to change.

let awardedPoints: Int = 100 - difference

And we just repeat that for these other items that don’t change. For awarded points we could do the same, by the way this is one of those cases where the error message in code is actually really good and even includes a fix it button.

I can click and it’ll replace the var with let for me which is really convenient sometimes.

let awardedPoints: Int = 100 - difference

The Issue navigator can be really helpful to find warnings in other files.

I can just click on this one under ContentView and it’ll take me right there.

Yeah, so on this line here we’re creating a rounded value. We set it to an initial value. We never changed it. So that’s an example of when we should have a let.

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

And if we remember in bullseye tests, we actually were creating a couple of variables here that never changed.

So, in both tests, change guess and score to constants with the let keyword.

let guess = game.target + 5
let score = game.points(sliderValue: guess)

Now, to make sure I’ve gotten all of them, I can check the Issue navigator here which shows all of the errors or warnings accross the project, and we don’t see any.

I’m just gonna make sure everything still works. Command + B to build, the Command + U to run our unit test, good practice to make sure we didn’t break anything.

So now we have our code following some best practices of using constant where possible rather than variables, and all our tests are passing!