0

I have a user data saved in UserDefaults, now I want to make an edit profile view and I want to use TextField to show current user data, but I get this error because I put the code inside the body Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols. I want to display all current user data inside the TextField, so they can see their data before make an edit. how to do that correctly?

MyCode

struct EditProfile: View {
    
    @AppStorage(CurrentUserDefaults.EMAIL) var currentUserEmail: String?
    @AppStorage(CurrentUserDefaults.USERNAME) var currentUserName: String?
    
    @State var userName = ""
    @State var userPhone = ""
    @State var userAddress = ""
    
    var body: some View {
        username = currentUserName ?? "" //[Error] I want to display currentUserName on the textfield
        NavigationView{
            VStack{
                TextField("Username", text: $userName)
            }.navigationBarTitle("Edit Profile")
        }.navigationViewStyle(StackNavigationViewStyle())
    }
}

1 Answer 1

2

If you're looking to set userName to the @AppStorage value and then change a temporary @State variable (maybe to be committed later), you could use onAppear to set it:

NavigationView{
            VStack{
                TextField("Username", text: $userName)
            }
            .navigationBarTitle("Edit Profile")
        }
        .navigationViewStyle(StackNavigationViewStyle())
        .onAppear {
            userName = currentUserName ?? ""
        }

You can't do inline code like the variable assignment you're trying to do inside a View's body because it's a special type of computed property (or function) called a ViewBuilder where the contents get automatically returned: https://developer.apple.com/documentation/swiftui/viewbuilder

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.