What are the fundamental differences between set and didSet?

后端 未结 2 1030
孤独总比滥情好
孤独总比滥情好 2021-01-17 14:27

I understand that one is a setter and the other is a property observer. My question is how do they differ in behavior and when would you use one over the other. Don\'t they

2条回答
  •  囚心锁ツ
    2021-01-17 14:46

    One more thing. :)

    set {} is calling when you initialise value, but not disSet {}

    var x : Int = 0 {
      set {
        print(x)
      }
    }
    ...
    x = 1
    

    produce "0" and "1" output.

    But didSet not so.

    var x : Int = 0 {
      didSet {
        print(x)
      }
    }
    ...
    x = 1
    

    have not call before you change value. Only "1" result will be printed, not "0" and "1"

    It can be as useful, so bug source.

提交回复
热议问题