Your First iOS & SwiftUI App: An App from Scratch
Jan 11 2022 Swift 5.5, iOS 15, Xcode 13
Part 2: SwiftUI Data
Leave a rating/review
This video Variables was last updated on Jan 11 2022
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!” This 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. You can think of it like casting a harry potter-style magic spell to convert one type to another. “Expecto Convertum!”
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.
Allright - that’s enough about theory - let’s go back to code.
Update code to:
var roundedValue: Int = Int(self.sliderValue) return Alert( title: Text("Hello there!"), message: Text("The slider's value is \(self.sliderValue), rounded Value is \(roundedValue)."), dismissButton: .default(Text("Awesome!")))
Mention warning - say you’ll explain what this is about later in the course.
Show how that doesn’t actually round it - it just truncates it.
Cmd-Click on the Double sliderValue \ Show Quick Help \ Open Developer Documentation. Show that Double has a rounded method, and click it to show an example of how to use it.
Modify code as follows:
var roundedValue: Int = Int(self.sliderValue.rounded())
Build & run, show it works.
Update message to:
message: Text("The slider's value is \(roundedValue)."),