将值设置为SWIFT中的计算属性

12 properties ios swift

我正在尝试学习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)")
        }
Run Code Online (Sandbox Code Playgroud)

编辑:但是我发现我可以更改其派生的计算属性的其他属性

set(newValue){
           // self.area = newValue
            width = newValue/10
            println("the new width for computed properties is as \(width)")
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,如果我想改变计算属性iteself,该怎么办?

Mar*_*n R 12

计算属性就是:计算值,在您的情况下从宽度和高度.没有存储属性值的实例变量,您不能更改"计算属性本身".

这没有任何意义:如果该区域可以设置为不同的值,那么getter方法应该返回什么?这个新值还是width*height

所以很可能你想要一个区域的只读计算属性:

var area: Int {
    get {
        return width * height
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您已经注意到的,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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但即便如此,结果可能会令人惊讶(由于整数舍入):

let r = Rectangle()
r.area = 200
println(r.area) // 196
Run Code Online (Sandbox Code Playgroud)


wlt*_*rup 10

我认为你误解了计算属性的概念.根据定义,计算属性是您无法设置其值的属性,因为它是计算出来的.它没有独立存在.计算属性中setter的目的不是设置属性的值,而是设置计算计算属性的其他属性的值.以广场为例.它的边长是一个var属性s,该区域是一个计算属性,其getter返回s*s,其setter设置为newValue(新区域)的平方根.设定者不设定区域.它设置下次访问area属性时计算区域的边长.