如何找出在 willSet / didSet 更新了元组的哪个变量?

How to find out which variable of a tuple was updated at willSet / didSet?

如何找出元组的哪个变量在 willSet / didSet 被更新了?

var myTuple: (a: Int, b: Int) {
   didSet {
      // Which one was set, a or b?
   }
}

实际上,您将使用 willSet 获取更新后的值,并使用桥接到 newValue.a.b)的元组属性访问内容:

var myTuple: (a: Int, b: Int) {
    willSet {
        print(newValue.a)
        print(newValue.b)
    }
}

您可以像这样比较值,例如:

var myTuple: (a: Int, b: Int) {
    willSet {
        if newValue.a != myTuple.a {
            print(".a changed")
        }
        if newValue.b != myTuple.b {
            print(".b changed")
        }
    }
}

你可以这样检查旧值

    var myTouple: (a: Int, b: Int) {
   didSet {
      print(oldValue.a)
      print(oldValue.b)
   }
}

并比较它们。如果你只设置一个元组的值,比如

myTouple.a = 5

就好像你设置了所有,其余的都得到了它们的旧值,就像你写的一样

myTouple = (5, myTouple.b)