What is a variable?
We can think of variables as "boxes" where we can store data while our App is running like a user's name, their age, or other things like the number of cars currently in a garage. For example, when a user types their name on the keyboard, our code will assign that value to a variable so we can work with it (display it on screen, save it to a database, etc...).
Declaring a variable
To use a variable, we first need to declare it and assign a value to it.
@State var myAge: Int = 35
To do this, you need to specify 5 things:
@State
. This concept will be explained in upcoming articles.var
is the Keyword that indicates that it is a variable.myAge
is the name of the variable that we'll use to refer to it later, so it must be unique.Int
is type of the variable. For now, we'll useInt
for integer numbers andString
for text.=
is the command that assigns a value to our variable.35
is, in this case, the initial value we assign to our variable.
@State var myFirstName: String = "Pablo"
String
), we enclose it in quotation marks so Xcode knows it’s not code, but simple text.
Where to declare our variables
Variables must be declared inside the view but outside the body
.
import SwiftUI
struct ContentView: View {
@State var myFirstName: String = "Pablo"
@State var myAge: Int = 35
var body: some View {
Text("Hello World!")
}
}
#Preview {
ContentView()
}
Accessing the variable's value
Once our variables are defined, to access the value that they store ("Pablo" and 35) we do so by using the variable’s name, like myFirstName
or myAge
.
You can access these variables at any time and from any element, which is the main advantage of using variables.
We can use a variable instead of a simple String
in a Text
element.
Text(myFirstName)
The type of variable is important, as Text()
only accepts String
inside its parentheses.
However, we can "inject" any variable into a String
by using \()
.
Text("\(myAge)")
Let’s look at a complete example.
import SwiftUI
struct ContentView: View {
@State var myFirstName: String = "Pablo"
@State var myAge: Int = 35
var body: some View {
VStack {
Text("My name is \(myFirstName)")
Text("I am \(myAge) years old")
}
}
}
#Preview {
ContentView()
}
Editing a variable
When your code is running (which we will now call Run Time), the value of a variable can change.
To change its value, you don’t need to declare it again, as that is done only once per variable. You just need to assign another value to it using the =
operator.
myAge = 12
To put this into practice, let’s see how we can assign new values to our variables using a button action.
import SwiftUI
struct ContentView: View {
@State var myFirstName: String = "Pablo"
@State var myAge: Int = 35
var body: some View {
VStack {
Text("My name is \(myFirstName)")
Text("I am \(myAge) years old")
Button {
myFirstName = "Fernando"
} label: {
Text("Change name")
}
Button {
myAge = 12
} label: {
Text("Change age")
}
}
}
}
#Preview {
ContentView()
}
Be the first to comment