Suppose I have an enum case with an associated value, and two variables of that enum type:
enum MyEnum {
case foo, bar(_ prop: Int)
}
let var1 = MyEnum.foo
let var2 = MyEnum.bar(1)
If I want to check if both variables match the general case with the associated value, I can do that with a comma:
if case .bar = var1, case .bar = var2 {
print("both are bar")
}
But I need to check if either matches the case, with something like this:
if case .bar = var1 || case .bar = var2 {
print("at least one is bar")
}
However, that doesn't compile. Is there another way to write this to make the logic work?
Excel Logical Test Using Multiple If Statements in Excel [AND/OR] By Steve. To test certain conditions, people use If statement. The If () function is used to perform logical tests and to evaluate conditions that will show two outcomes. This Excel IF statement is used to analyze a condition that will show two outcomes.
Basically, excel logical test is used to evaluate the condition whether it is true or false. An IF statement is mainly used to test any condition that will give you more than two outcomes.
Multiple If Statement in Excel for Four Outcomes. In these four outcomes, you require three different conditions. Excel If statement multiple conditions range tests a single condition and returns an outcome. Syntax =IF(Condition A, Output Y, IF (Condition B, Output Z, IF (Condition C, Output R, Output S))))
This is the simple or basic If statement which is used to test conditions that can return two results i.e, either TRUE or FALSE. Let’s take a data set which is shown above.
I would resort to some sort of isBar
property on the enum itself, so that the "a or b" test remains readable:
enum MyEnum {
case foo, bar(_ prop: Int)
var isBar: Bool {
switch self {
case .bar: return true
default: return false
}
}
}
let var1 = MyEnum.foo
let var2 = MyEnum.bar(1)
let eitherIsBar = var1.isBar || var2.isBar
You have to implement Equatable protocol for your enum:
extension MyEnum: Equatable {}
func ==(lhs: MyEnum, rhs: MyEnum) -> Bool {
switch (lhs, rhs) {
case (let .bar(prop1), let .bar(prop2)):
return prop1 == prop2
case (.foo, .foo):
return true
default:
return false
}
}
Then the following code should work:
if var1 == .bar(1) || var2 == .bar(1) {
print("at least one is bar")
}
UPD: In case if you don't need to check associated value, you can do pattern matching like this:
switch (var1, var2) {
case (.bar, _), (_, .bar): print("at least one is bar")
default: break
}
My solution for this sort of thing is:
if [var1, var2].contains(.bar) {
A lot of the time I want it the other way, a single var that might be filtered based on several values:
if [.bar, .baz].contains(var)
but indeed, if there are associated values involved you have to make them equatable and define an operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With