Computed Variables
Use on SwiftUI views.
Computed Variables
Use on SwiftUI views.
0
0
Checkbox to mark video as read
Mark as read

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)"
}


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()
}

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy