0

I want capture the associated value with enum case in if statement, here is my code:

enum TestEnum: Equatable {
    case a, b(value: String)
}

func f35() {
    let my: TestEnum = TestEnum.b(value: "Hello")

    if my == .b(value: let string) {
        print(string)
    }
    
}

Xcode does not help me to solve the issue.

ios coder
  • 1
  • 4
  • 31
  • 91
  • 1
    https://stackoverflow.com/questions/31359142/how-to-access-a-swift-enum-associated-value-outside-of-a-switch-statement ? – Larme Mar 01 '23 at 15:38
  • if you don't want to do a switch and want to use an if (i personally find this cleaner since it looks more like an unwrapping of a value): `if case .b(let value) = my { /* do something with "value" */ }` – kbunarjo Mar 02 '23 at 03:55

1 Answers1

0

You can use a switch statement to capture the enum values and then use this switch statement inside the if statement like this.

enum TestEnum: Equatable {
case a, b(value: String)
}

func f35() {
let my: TestEnum = TestEnum.b(value: "Hello")

switch my {
case .b(let string):
    print(string)
    if string == "Hello" {
        // do something
    }
default:
    break
}
}
  • 1
    Thanks, your code is very very very very advanced, I cannot use so advanced code because my mac would explode. – ios coder Mar 01 '23 at 15:47