gpt4 book ai didi

ios - Swift:如何直接设置对象的属性?

转载 作者:行者123 更新时间:2023-11-28 09:20:10 25 4
gpt4 key购买 nike

这是 Apple 文档中的代码:

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)
}
}

如果我遵循文档,

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 不是 willSeted:

triangleAndSquare.square.sideLength //50.0 

似乎 willSet 需要绑定(bind)到 trianglesquare,因为 square.sideLength = newValue.sideLength

如果我设置了square的属性,我如何才能直接改变triangle的属性,而不是创建一个新的Square 对象?

最佳答案

它没有像您预期的那样工作,因为 willSet & co.作用于实际属性(在本例中为 trianglesquare)变化。因为它们是类,修改它们的属性不会改变代表它们的类指针,只会改变它的内容依次指向的地方(即它是相同的三角形和正方形,而不是新实例)。

要做你想做的事,你必须子类 SquareTriangle 以在属性的这些子类中提供 willSet你想观察。为了使其按预期工作,每个子类都必须有一个新属性(比如 brother: NameShape ),您必须在复合类的 init 中设置该属性, 这样他们就可以改变彼此的属性。

关于ios - Swift:如何直接设置对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25418408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com