我正在尝试学习 swift 中的计算属性..并且知道我需要 setter 来设置计算属性的值..我正在尝试但是卡住了..请帮助我如何在具有 setter 属性的区域中设置值。 ..如果你能告诉我如何使用 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)")
}
}
但是如果我想自己更改计算属性怎么办
最佳答案
一个计算属性就是:一个计算值,在你的例子中来自 宽度和高度。没有属性所在的实例变量 值已存储,您无法更改“计算属性本身”。
这毫无意义:如果区域可以设置为不同的值,
getter 方法应该返回什么?这个新值还是 width*height
?
所以很可能您想要该区域的只读计算属性:
var area: Int {
get {
return width * height
}
}
正如您已经注意到的,setter 可以修改其他对象的值 存储属性,例如:
class Rectangle {
var width : Int = 20
var height : Int = 400
var area: Int {
get {
return width * height
}
set(newArea){
// Make it a square with the approximate given area:
width = Int(sqrt(Double(newArea)))
height = width
}
}
}
但即便如此,结果也可能令人惊讶(由于整数舍入):
let r = Rectangle()
r.area = 200
println(r.area) // 196
关于ios - 将值设置为 SWIFT 中的计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29690521/