A Computed Variable is a variable similar to the ones weโve seen before. However, instead of assigning a value using the =
symbol, we define its value using a block of code enclosed in curly braces { }
.
var fullName: String {
return "Pablo Guardiola"
}
The main advantage is that within this block, we can execute multiple lines of code.
var age: Int = 17
var parentalPermission: Bool = true
var allowAccess: Bool {
var isOfLegalAge: Bool = age >= 18
return isOfLegalAge || parentalPermission
}
We can also use other variables within the computed variable.
var name: String = "Pablo"
var lastName: String = "Guardiola"
var fullName: String {
return "\(name) \(lastName)"
}
name
or lastName
, the value of this variable will update "automatically".
As you can see, the last line of code in this block needs to include the return
keyword. However, if the block contains only one line of code, we can omit this:
var fullName: String {
"\(name) \(lastName)"
}
They've Always Been There
You may have noticed that our ContentView
has a Computed Variable called body
where we include all our UI components. This variable follows the same pattern, but the difference is that it returns a type of variable we havenโt seen yet: some View
.
We'll explain why this type exists later, but for now, it's important to know that we can create variables just to better organize our views.
import SwiftUI
struct ContentView: View {
@State var name: String = "Pablo"
@State var lastName: String = "Guardiola"
var body: some View {
VStack {
nameView
lastNameView
}
}
var nameView: some View {
Text(name)
}
var lastNameView: some View {
Text(lastName)
}
}
#Preview {
ContentView()
}
Be the first to comment