在didSet中,对于Swift中的枚举属性,是否可以检查新值是否与旧值相同?

时间:2018-04-22 13:37:27

标签: swift enums

给出以下示例:

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
    }
}

我无法比较ViewState类型的两个属性,因为我的一个案例中有一个关联值,所以我无法使用原始值进行比较。

我正在寻找的方法是检查新值是否为新值或与当前值相同。这可能吗?

1 个答案:

答案 0 :(得分:1)

使用willSet并执行类似的操作

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

输出为
  空闲 - >积极
  有效 - >完成(“我们已经完成”)