jeudi 22 mars 2018

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...")
}

Aucun commentaire:

Enregistrer un commentaire