Leave a rating/review
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 will often replace its contents with a new value. For example, maybe you want to put a rabbit in the hat instead.
That’s the whole point behind variables: they can vary. For example, the sliderValue state variable that you created value 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, any time 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 private.
-
The first required element is the keyword var, which is short for variable, and means it can change. In contrast, if you know the variable will not 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.
- You then enter 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.
-
You then 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 be either 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’s state, so we marked it with @State. It is named “sliderValue”, and its type is Double. This means we can store double values - that is, decimal values like 3.1415, into this variable. We could not store a string value into 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 the Int, you’ll get an error. This is because Swift says - ‘Hey wait a minute, 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 you helps prevent mistakes in your coding, and is called type safety.
So instead, you have to be explicit about your conversions. It turns out you can create a new Int given a float value, like you see here. The conversion discards any of the decimal component, so in this case y would be set to 3.
This process of converting from one type to another is sometimes called casting.
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 this 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 go back to code.
Alight, so what we’re trying to do is we’re trying to convert the slider value, which is a double, in other words, a number with decimal points to an integer value which has no decimal points.
To do that, we’re going to create a new variable.
So far all of our variable has 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. 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 with the upper case letter.
And I’m going to put a : and we’re going to say this is a variable of type Int, which means integer.
And let me set 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 wanna convert which is slidervalue.
var roundedValue: Int = Int(sliderValue)
Okay, so now we can modify our message a little bit and show both the original slider value with decimal points and we’ll also show the rounded value.
So the sliders value is sliders value and then before the period here, we’re going to say and rounded value is, and then we’re going to use string interpolation again.
So , two parentheses and inside there, we’re going to put in rounded value. So this is what’s called local scope.
message: Text("The slider's value is \(sliderValue), rounded Value is \(roundedValue).")
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 let me just drag it a little bit more here. I wanna show you something.
Okay, let’s check this out. We see the slider’s value is 70.79 etc 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 X-code has some great built-in developer documentation. And often if you wanna see what something is, you can 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 slider value, it will say what this is and it’s saying; hey, you’re looking at a property called slider value which was returning the double.
And as I moved 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, whoa, 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 in that case.
That’s what we want. So in the variable after slider value, start typing dot round. And then just hit, Enter, auto-complete will pick it up.
var roundedValue: Int = Int(sliderValue.rounded())
So to sum up what’s going on here is, 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 property.
Now that we have it working the way we want, we can clean this up a little bit. So we can just say the sliders value is rounded value and delete all this other stuff. We don’t need it anymore.
message: Text("The slider's value is \(roundedValue)."),
Try it one more time to make sure it works. Drag the slider around there and hit the button.
Perfect!