Edward Brey
Edward Brey

Reputation: 41648

Associated enum state in SwiftUI

How can I use an associated enum as a @State variable in an if statement in SwiftUI?

struct ProfileView: View {
    @State private var choice = Choice.simple

    private enum Choice {
        case simple
        case associated(Int)
    }

    var body: some View {
        if choice == .simple {
            Text("Simple")
        }
    }
}

The compiler reports this error:

Protocol 'Equatable' requires that 'ProfileView.Choice' conform to 'Equatable'

Upvotes: 4

Views: 5734

Answers (2)

Asperi
Asperi

Reputation: 257709

Here is fixed variant. Tested with Xcode 11.4.

struct ProfileView: View {
    @State private var choice = Choice.simple

    private enum Choice: Equatable {
        case simple
        case associated(Int)
    }

    var body: some View {
        Group {
            if choice == .simple {
                Text("Simple")
            } else {
                Text("Other")
            }
        }
    }
}

Upvotes: 5

David Pasztor
David Pasztor

Reputation: 54716

You need to use if case to check if an enum variable matches a certain case.

var body: some View {
    if case .simple = choice {
        return Text("Simple")
    } else {
        return Text("Not so simple")
    }
}

If you actually want to use the associated value to be displayed, I'd suggest using a switch to cover all enum cases.

var body: some View {
    let text: String
    switch choice {
    case .simple:
        text = "Simple"
    case .associated(let value):
        text = "\(value)"
    }
    return Text(text)
}

Upvotes: 5

Related Questions