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

标签 ios swift properties

我正在尝试学习 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/

相关文章:

vba - 让 VBA 类模块的属性 - 是否可以有多个参数?

ios - 何时/如何设置 UIImageView contentMode(UIImageView setContentMode 不起作用)

ios - CollectionViewLayout 补充 View 高度等于内容

arrays - Swift 3 访问 json 提要中的嵌套字典

ios - 如何使用 Swift 和 SpriteKit 使 View 可滚动以查看带有 Sprite 的完整场景?

ios - 更改 UIView 在 captureOutput 中的位置

spring-mvc - Spring MVC application.properties 未被配置文件 application-dev.properties 覆盖

iphone - 如果我使用@property,还需要声明实例变量吗?

ios - 当我尝试更改 UIlabel 的文本时,我在 Swift 中得到 "unexpectedly found nil while unwrapping value"

ios - 缩放超过 ImageView 边界