加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 懒惰的计算变量

发布时间:2020-12-14 04:34:43 所属栏目:百科 来源:网络整理
导读:我正在尝试制作一个具有惰性计算变量幅度的Vector结构,但我似乎无法找到一种方法来实现它. 这就是我所拥有的: struct Vector { var x: Double = 0.0 { didSet { magnitudeActual = -1.0 } } var y: Double = 0.0 { didSet { magnitudeActual = -1.0 } } var
我正在尝试制作一个具有惰性计算变量幅度的Vector结构,但我似乎无法找到一种方法来实现它.

这就是我所拥有的:

struct Vector {

    var x: Double = 0.0 {
        didSet {
            magnitudeActual = -1.0
        }
    }
    var y: Double = 0.0 {
        didSet {
            magnitudeActual = -1.0
        }
    }

    var magnitudeActual: Double = 0.0

    var magnitude: Double {
        if magnitudeActual < 0.0 {
            magnitudeActual = sqrt(x * x + y * y) //cannot assign to "magnitudeActual" in self
        }
        return magnitudeActual
    }

    init() {}

    init(_ x: Double,_ y: Double) {
        self.x = x
        self.y = y
    }

}

我已经尝试了许多方法来实现这一点,但似乎没有任何工作.另外,一个willGet会很好,但不存在.

解决方法

From the docs:

Modifying Value Types from Within Instance Methods

Structures and enumerations are value types. By default,the properties of a value type cannot be modified from within its instance methods.

However,if you need to modify the properties of your structure or enumeration within a particular method,you can opt in to mutating behavior for that method. The method can then mutate (that is,change) its properties from within the method,and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property,and this new instance will replace the existing one when the method ends.

那么,除非执行修改的函数被标记为变异,否则结构不能自行修改.这意味着您需要为属性定义正确的get函数.

var magnitude: Double {
mutating get {
    if magnitudeActual < 0.0 {
        NSLog("Recalc") // just to make sure it's caching the result properly.
        magnitudeActual = sqrt(x * x + y * y)
    }
    return magnitudeActual
}
}

现在我们可以做到这一点

var v = Vector(3,4)
v.magnitude // Recalc 5
v.magnitude // 5

v.x = 5
v.y = 12
v.magnitude // Recalc 13

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读