1

I'm very new to swiftui so I don't know if I'm doing completely wrong but the error is not helpful. Here is my code:

import SwiftUI

struct IntroScreenP2: View {
 var hasName: Bool = false
 @State private var firstName: String = ""
 @State private var lastName: String = ""
 var body: some View {
  VStack {
   if firstName != "" && lastName != "" {
    hasName = true
   }
   TextField("First Name", text: $firstName)
    .padding(.leading)
    .padding(.bottom, 5)
   Divider()
   TextField("Last Name", text: $lastName)
    .padding(.leading)
    .padding(.top, 5)
   }
  }
}

I'm just trying to set a boolean equal to true when the user enters their name in the text field. It keeps giving me an error saying "Type of expression is ambiguous without more context"

2 Answers 2

1

you cannot just "code" as usual in SwiftUI. SwiftUI requires that you return Views. Maybe you should read some Introduction and Tutorials to SwiftUI.

Here is the code "corrected". If you tell me what you want with your variable i can help you further more.

struct ContentView: View {
    @State var hasName: Bool = false
    @State private var firstName: String = ""
    @State private var lastName: String = ""
    var body: some View {
        VStack {
            if firstName != "" && lastName != "" {
              Text("Has name")
            }
            TextField("First Name", text: $firstName)
                .padding(.leading)
                .padding(.bottom, 5)
            Divider()
            TextField("Last Name", text: $lastName)
                .padding(.leading)
                .padding(.top, 5)
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It would be incorrect to define hasName with @State. @State introduces a new source of truth, whereas here it should be a derived value, computed from firstName and lastName. This could be done by either making it a computed property, or by using didSet observers on firstName and lastName to update it after every change.
1

You don't need to set it at all! Just make it computed:

var hasName: Bool { firstName != "" && lastName != "" }

Note that it's better to use .isEmpty instead:

var hasName: Bool { !firstName.isEmpty && !lastName.isEmpty }

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.