Your First iOS & SwiftUI App: An App from Scratch

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

Part 2: SwiftUI Data

16. Variables

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: 15. Strings Next episode: 17. Intro to App Architecture

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.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

In order to understand how to convert a decimal value to a whole number, you need to understand how variables and data types work in Swift. A variable allows the app to remember things. Think of a variable as a temporary storage container for a single piece of data like this image of a hat that I put a cute creature in. You don't just put stuff in the container and then forget about it. You'll often replace its contents with a new value. For example, maybe you want to put a rabbit in a hat instead. That's the whole point by in variables, they can vary. For example, the sliderValue state variable that you created will change every time the slider is moved. You configure each variable to store a certain type of data. For example, this hat stores cute creatures. You can think of variables like children's toy blocks. The idea is to put the right shape into the right container. The container is the variable and its type determines what shape fits. The shapes are all the possible values that you can put into the variables. Here's the syntax to create a variable in Swift. If this variable is a property on a SwiftUI view, you can add the @State keyword. This tells Swift that this variable contains important app state. Remember, anytime a state variable changes, SwiftUI automatically recomputes the body of the view so that the body is always up to date with the state. If this variable is a property on a class or struct, you can optionally put private if you want to mark a variable as private to this particular class or struct. You'll learn more about what this impacts as well as other options besides private later on in this learning path. But for now, just know that it's a best practice to mark state variables as private. The first required element is the keyword var, which is short for a variable and means it can change. In contrast, if you know that the variable will never change, you can use the keyword let instead. We'll talk more about var versus let later in this course. For now, just know that sometimes we'll use var and sometimes we'll use let, but they both store data. Then you have the name of the variable. You can name it anything you like as long as you avoid special keywords in Swift like var or func. Usually in Swift, it's best practice to name your variables with camel case, which means you start out in lowercase and if your variable has multiple words, the first letter of any subsequent word is uppercased but that's just a best practice. In the end, it's up to you. Then you enter a colon and enter the type of the variable. For example, one type you've worked with already is bool which is a variable that can either be true or false. Finally, optionally, you can set the variable to an initial value. For example, here's the line of code we just wrote to create a variable to store the slider's value. This variable stores part of the app state, so we marked it with @State. It's named sliderValue and its type is double. This means we can store double values, that is decimal values like 3.1415 in this variable. We could not store a string value in this variable. You may wonder how you can convert one type to another. For example, we want to convert this double value into a whole number, which is called an int in Swift. Well, if you try to simply assign the double to an int, you'll get an error, and this is because Swift says, Hey, wait a second, this is an int-shaped container and you can't put a double into it. While this can seem a little silly with numbers, it is a good thing as it helps prevent mistakes in your coding and it's called type safety. So instead, you have to be explicit about your conversions. It turns out that you can create a new int given afloat value, like you see here. The conversion discards any of the decimal components. So in this case, y would be set to three. There's one last thing I'd like to mention. I said a variable is a temporary storage container but how long will it keep its contents? Well, each variable has a certain lifetime that depends on exactly where in your program you define that variable. In this case, sliderValue sticks around for just as long as its owner contentView does. Their fates are intertwined. The contentView and thus sliderValue are there for the duration of the app. They don't get destroyed until the app quits. There are also variables that are short lived, also known as local variables. In a minute, I'll show you how you can add a local variable in your app. The concept of how long a variable lives is called scope and we'll talk much more about how this works later in the course. For now, all you need to know is that whenever the user moves the slider, SwiftUI automatically updates the sliderValue with the current value of the slider. So they always match, and then when we display the alert, we can access the latest value. All right, that's enough about theory. Let's get back to the code. So what we're trying to do is we're trying to convert the sliderValue, which is a double, in other words, a number with decimal places to an integer value, which has no decimal places. To do that, we're going to create a new variable. So far, all of our variables have been properties of contentView, but we can also make temporary variables that are inside the scope of a button's action or inside of the alert. We only want the rounded value for the slider in the alert. So we should put the variable there. It's a bit simpler than our state variables. Type in var and then a name, and we're going to call it rounded value and we use camel case in here, which means start lowercase and then every new word starts uppercase. And I'm going to put a colon and we'll say this is a variable of type int, which means integer, and then set it equal to an initial value, which we're going to put int and then parentheses. And this allows us to convert a double value to an integer. Inside these parentheses, we're going to parse the double value we want to convert, which is sliderValue. So now we can modify our message a little bit and show both the original sliderValue with decimal points and we'll also show the rounded value. So the slider's value is sliderValue, and then before the period, we're going to say the rounded value is. And then we'll use string interpolation again. So slash and then two parentheses. And inside here, we're going to put in roundedValue. So this is what's called local scope. All right, let's run this for a second and see what's going on so far. So right in the canvas, with the live mode on, tap Hit Me, and I can see here in the alert that we have the long decimal number and then we have a truncated integer number here. But lemme just drag it a little bit more here and I wanna show you something. Okay, let's check this out. We see the slider's value is 70.79, et cetera, et cetera. So if it's truly a rounded value, this should be 71, not 70, right? But when you're using this way of converting, it's actually just truncating it. It's not rounding it. So let's see how we can actually make it rounded instead. Remember that Xcode had some great built-in developer documentation and often if you want to see what something is, you can just hold Option and this little question mark will come up and it'll give you a dynamic help based on what you click on. So if I hold Option and click on sliderValue, it will say what this is and it's saying, hey, you're looking at a property called sliderValue, which was returning a double. And as I move my mouse over different things here, sometimes I can click to get more information. So I can click on double and it'll take me straight to the documentation for double. And this will let me see different things I can do with double values, like creating random numbers, creating square roots. And if I scroll down, this looks like what we want. There's a method we can call on double that will return us a rounded version of the double value. So for example, if I had 56.7 and I called rounded on it, it would give me 57, and that's what we want. So in the variable after sliderValue.round and then just hit enter, auto complete will pick it up. So to sum up what's going on here, if we have a value like 56.7, which is a double, so to sum up what's going on here, if we have a value like 56.7, which is a double, sliderValue.rounded will make it 57.0. And if we wrap it in this int, it'll cut off the decimal and just make it an integer of 57, which is exactly what we want. So let's try it in the canvas again and we can see that this is now rounding properly. Now that we have it working the way we want, we can clean this up a little bit. So we can just say the slider's value is rounded value and delete all this other stuff. We don't need it anymore. Try it one more time to make sure it's working. Drag the slider around here and hit the button. Perfect.