这是来自Apple的Doc:
的代码class NameShape{
var numberOfSide: Int = 0
var name:String
func simpleDescription() -> String {
return "A square with \(numberOfSide) sides."
}
init (name: String){
self.name = name
}
}
class Square:NameShape{
var sideLength: Double
init(name: String, sideLength: Double){
self.sideLength = sideLength
super.init(name: name)
numberOfSide = 4
}
func area() ->Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}
class EquilateralTriangle:NameShape{
var sideLength: Double = 0.0
init(sideLength: Double, name: String){
self.sideLength = sideLength
super.init(name: name)
numberOfSide = 3
}
var perimeter: Double{
get{
return 3.0 * sideLength
}
set{
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
class TriangleAndSquare{
var triangle:EquilateralTriangle{
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square{
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String){
square = Square(name: name, sideLength: size)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
如果我关注Doc,
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
triangleAndSquare.square.sideLength //10.0
triangleAndSquare.triangle.sideLength //10.0
triangleAndSquare.square = Square(name: "larger square", sideLength: 50)
triangleAndSquare.triangle.sideLength //500.0
但如果我只是更改triangle.sideLength
:
triangleAndSquare.triangle.sideLength = 25
triangleAndSquare.triangle.sideLength //25.0
但square.sideLength
不是willSet
ed:
triangleAndSquare.square.sideLength //50.0
似乎willSet
需要绑定到triangle
或square
,因为square.sideLength = newValue.sideLength
如果我设置了triangle
的属性,但是没有创建新的square
对象,我怎样才能直接更改Square
的属性?
答案 0 :(得分:0)
它没有像您期望的那样工作,因为willSet
&合。对实际财产(在这种情况下为triangle
& square
)进行更改。由于它们是类,修改它们的属性不会改变表示它们的类指针,只会改变它的内容依次指向它(即它是相同的三角形和正方形,而不是新实例)。
要做你想做的事,你必须继承类Square
& Triangle
在您要观察的属性上为这些子类提供willSet
。为了使它按预期工作,每个子类都必须有一个新属性(比如brother: NameShape
),你必须在复合类的init
中设置它们,这样它们就可以互相改变了属性。