ObjC/Swift 写了段 swift 代码,以为会死循环

ane · 2014年10月01日 · 最后由 luikore 回复于 2014年10月01日 · 7292 次阅读
class TriangleAndSquare {
    var triangle: EquilateralTriangle {
    willSet {
        square.sideLength = newValue.sideLength
        println("--------")
    }
    didSet {
        println("------++++++")
        Square(sideLength: 50, name: "larger square")
    }
    }
    var square: Square {
    willSet {
        println("++++++++++++")
        triangle.sideLength = newValue.sideLength
    }
    didSet {
        println("+++++----------")
        EquilateralTriangle(sideLength: 150, name: "larger TriangleAndSquare")
    }
    }
    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.triangle = EquilateralTriangle(sideLength: 150, name: "larger TriangleAndSquare")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength

原以为会死循环,可貌似没有,有清楚机制的吗?

init 或者设置初始默认值时, 不会调用 willset 和 didset 回调的

另外设置属性的属性, 不算改变了属性, 所以不会触发回调

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册