Search code examples
swiftswiftuiswiftui-state

Set variable based on @State properties


Inside my View struct, I have the following @State properties:

@State private var email = ""
@State private var password = ""

And multiple times in the View body I repeat this code to check whether the login button should be disabled:

email.isEmpty || password.isEmpty

From what I have tried, trying to set isDisabled within the View body gives:

Type of expression is ambiguous without more context

Is there a way I can add a variable within the View struct like isDisabled so I don't need to repeat this logic?


Solution

  • Thanks to @Asperi, all I needed was a Computed Property:

    private var isDisabled: Bool {
        email.isEmpty || password.isEmpty
    }