[swift-users] strange property observer behavior

adelzhang at qq.com adelzhang at qq.com
Sun Sep 4 05:25:25 CDT 2016


Hi all

It sounds convenient to monitor change in property's value using property  
observer.
But TSPL(The Swift Programming Language) talk little about property  
observer. There
are some questions abouts property observer.

1) when `didSet` observer will call?

I assume it's fine that changing property's value in `didSet` observer.

     class Foo {
         var a: Int = 0 {
             didSet {
                 print("didset")
                 a = a + 1
             }
         }
     }

     let foo = Foo()
     foo.a = 4  // only output "didset" once

Why it don't cause infinite loop?

2) infinite loop

     // this code snippet cause inifinite loop
     class Foo {
         var a: Int = 0 {
             didSet {
                 b = a + 1
             }
         }

         var b: Int = 1 {
             didSet {
                 a = b - 1
             }
         }
     }

     let foo = Foo()
     foo.a = 2

3) override property observer

     class Base {
         var a: Int = 0 {
             didSet {
                 print("base didset")
             }
         }
     }

     class Child : Base {
         override var a : Int {
             didSet {
                 print("child didset")
             }
         }
     }

     let child = Child()
     child.a = 2 // output "base didset" and "child didset"
     let base = child as Base
     base.a  = 4 // still output "base didset" and "child didset"

Why overriding property observer still call parent's `didSet` observer?

--
Adel




More information about the swift-users mailing list