Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum if-else Comparisons

How can I perform the proper comparison check in the following code?

enum Location {
    case ontop
    case inside
    case underneath
}

struct Item {
    var location: Location?

    func checkStuff(currentLocation: Location?) {
        if case .ontop = currentLocation {
            // DO SOME STUFF
        }
    }
}

// currentLocation is optional, and initially nil
var currentLocation: Location?

var item1 = Item(location: .ontop)
item1.checkStuff(currentLocation: currentLocation)

currentLocation = item1.location

var item2 = Item(location: .inside)
item2.checkStuff(currentLocation: currentLocation)

So there is a struct, which 1 of its properties is an enum Location so that it can only have 1 of 3 values.

The struct has a method that takes action if an instance's location property is the same as an externally provided value of the same type that is the current status of the Location (from another instance of the same object type).

I cannot get the correct syntax to get into the right section of the if statement.

I have also tried unwrapping the optional currentLocation:

if let tempCurrentLocation = currentLocation {
     if case tempCurrentLocation = Location.ontop {
          print("Currently ontop")
          location = .ontop
     } else {
          print("Currently NOT ontop")
          location = .inside
     }
} else {
     print("Not able to unwrap enum...")
}
like image 927
jingo_man Avatar asked Jul 25 '26 08:07

jingo_man


1 Answers

It's important to note that currentLocation is not a Location, it's a Location? (a.k.a. Optional<Location>). So you have to pattern match against the cases of Optional first, not of Location. Then, within the patterns of Optional's cases, you can match against the various cases of Location.

Here is the progression of syntactic sugar, starting with the most verbose, and arriving at the most succinct, common way of doing this:

  • if case Optional.some(.ontop) = currentLocation { ... }
  • if case .some(.ontop) = currentLocation { ... }
  • And finally, the preferred way: if case .ontop? = currentLocation { ... }

if case is only really ideal if you want to check for a very small subset of a large set of cases. If you need to check multiple cases, it's better to use a switch. The case patterns are the same:

switch currentLocation {
    case .onTop?: // ...
    case .inside?: // ...
    case .underneath?: // ...
    case nil: // ...
}
like image 100
Alexander Avatar answered Jul 28 '26 04:07

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!