1

I was wondering if I could have a case statement return a different value if a variable was true or false.

var variable = false
enum enumeraton {
    case thing
    var value: Int {
        switch self {
        case .thing:
            if variable = true {
                return 1
            }else {
                return 2
            }
        }
    }
}

is there anyway to do this?

3
  • Yes you can. You just need to access "Variable" from where you call value. So maybe make a function (func value(withVariable: Bool) -> Int), or access it from the method (a singleton?) Commented May 6, 2021 at 14:09
  • 1
    Shouldn't your if-else be if variable == true you seem to be missing an equals sign in the condition Commented May 6, 2021 at 14:10
  • Yes! Thank you Larme, that worked great Commented May 6, 2021 at 14:17

2 Answers 2

2

Depending on how you want to treat variable there are different solutions. If you want to read the value of variable when creating your enum variable/property you can use an associated value with the enum

var variable = false
enum Enumeraton {
    case thing(Bool)
    var value: Int {
        switch self {
        case .thing(let flag):
            return flag ? 1 : 2
        }
    }
}

let enumValue: Enumeraton = .thing(variable)
print(enumValue.value)

But if you want to read variable over time then a function that takes the boolean as an argument is better

enum Enumeraton {
    case thing

    func value(for flag: Bool) -> Int {
        guard self == .thing else { return 0 } // or some other action
        return flag ? 1 : 2
    }
}

let enumValue: Enumeraton = .thing
print(enumValue.value(for: variable))
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a solution that could work. Tested with Xcode 12.5 and Swift 5.4

var variable = false
enum enumeraton {
    case thing
    case other
    var value: Int {
        switch self {
        case .thing:
            if variable {
                return 1
            } else {
                return 2
            }
        case .other:
            return 0
        }
    }
}

let foo = enumeraton.thing
print(foo.value) //prints 2

variable = true
print(foo.value) //prints 1

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.