我正在尝试学习Swift中的计算属性,并了解到我需要setter来为计算属性设置值。但我现在遇到了困难,请帮帮我,如何使用setter属性设置area中的值?如果您能告诉我何时使用setter属性以及如何使用它,那就太好了。
class ViewController: UIViewController {
var width : Int = 20
var height : Int = 400
var area: Int{
get{
return width * height
}set(newarea){
area = newarea*10
//these line gives me an warning and area is not set
}
}
override func viewDidLoad() {
super.viewDidLoad()
println("\(width)")
println("\(height)")
println("\(area)")
// gives an error while setting value to computed properties... area = 5000
// for that we need getter and setter properties in area...
area = 490
println("the new area for computed properties is as \(area)")
}
编辑: 然而我发现我可以更改从中派生出来的其他计算属性的属性
set(newValue){
// self.area = newValue
width = newValue/10
println("the new width for computed properties is as \(width)")
}
}
但是如果我想要改变计算属性本身怎么办?