0

Given the following example:

enum ViewState {
    case idle
    case loading
    case caseWithAssociatedValue(String)    
}

class View {
    private var state: ViewState = .idle

    func setState(to state: ViewState) {
        guard state != self.state else { return }
        self.state = state
    }
}

I can't compare two properties of type ViewState and I can't use a raw value to compare as one of my cases has an associated value.

What I'm looking for is a way to check if the new value for state a new value or the same as the current value. Is this possible?

mike
  • 2,073
  • 4
  • 20
  • 31

1 Answers1

1

Use willSet and do something like this

enum State : Equatable {
  case idle
  case active
  case done(String)
}

class test {
  var x: State {  
    willSet {
      if x != newValue {
        print("\(x) -> \(newValue)")
      }
    }
  }

  init(_ x: State) {
    self.x = x
  }
}

let t = test(State.idle)
t.x = State.active
t.x = State.done("We're done")

Output is
idle -> active
active -> done("We\'re done")

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52