SwiftUI Variable that contains multiple variables

Viewed 452

Let's say I have the following two Views:

ContentView:

struct ContentView: View {
@State var firstName = "John"
@State var middleName = "Michael"
@State var lastName = "Doe"
var body: some View {
    TabView(){
        ProfileScreen(firstName: $firstName, middleName: $middleName, lastName: $lastName)
            .tabItem {
                Image("Profile")
            }.tag(0)
        HomeScreen()
            .tabItem {
                Image("Home")
            }.tag(1)     
    }
}}

and ProfileScreen:

struct ProfileScreen: View {
@Binding var firstName: String
@Binding var middleName: String
@Binding var lastName: String
var body: some View {
    VStack {
        Text(firstName)
        Text(middleName)
        Text(lastName)
    }
}}

Is there a way for me to contain all three variables (firstName, middleName, and lastName) inside another variable (let's call it userInfo), in order to save space and time so I don't have to bind three separate variables across separate Views?

1 Answers

You can just wrap all properties in one struct, like below

struct ContentView: View {
    @State var userInfo = UserInfo(firstName: "John", middleName: "Michael", lastName: "Doe")
    
    var body: some View {
        TabView(){
            ProfileScreen(userInfo: $userInfo)
                .tabItem {
                    Image("Profile")
                }.tag(0)
        HomeScreen()
            .tabItem {
                Image("Home")
            }.tag(1)
        }
    }
}

struct UserInfo {
    var firstName: String
    var middleName: String
    var lastName: String
}

struct ProfileScreen: View {
    @Binding var userInfo: UserInfo
    
    var body: some View {
        VStack {
            Text(userInfo.firstName)
            Text(userInfo.middleName)
            Text(userInfo.lastName)
        }
    }
}
Related