计算属性和使用闭包设置的属性之间的区别 [英] Difference between computed property and property set with closure

查看:18
本文介绍了计算属性和使用闭包设置的属性之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Swift 的新手.计算属性和设置为闭包的属性有什么区别?我知道每次都会重新计算计算属性.闭包有什么不同吗?即

I'm new to Swift. What is the difference between a computed property and a property set to a closure? I know a computed property gets recalculated each time. Is it different for the closure? i.e.

关闭:

var pushBehavior: UIPushBehavior = {
    let lazilyCreatedPush = UIPushBehavior()
    lazilyCreatedPush.setAngle(50, magnitude: 50)
    return lazilyCreatedPush
}()

计算:

var pushBehavior: UIPushBehavior {
    get{
        let lazilyCreatedPush = UIPushBehavior()
        lazilyCreatedPush.setAngle(50, magnitude: 50)
        return lazilyCreatedPush
    }
}

推荐答案

简而言之,第一个是通过闭包初始化的存储属性,该闭包在初始化时仅被调用一次.第二个是计算属性,每次引用该属性时都会调用它的 get 块.

In short, the first is a stored property that is initialized via a closure, with that closure being called only one time, when it is initialized. The second is a computed property whose get block is called every time you reference that property.

存储属性的初始化闭包只会被调用一次,但您可以稍后更改存储属性的值(除非您将 var 替换为 let).当您想在单个简洁的代码块中封装代码以初始化存储的属性时,这很有用.

The stored property’s initialization closure is called once and only once, but you can later change the value of the stored property (unless you replace var with let). This is useful when you want to encapsulate the code to initialize a stored property in a single, concise block of code.

然而,每次引用变量时都会调用计算属性块.当您希望每次引用计算属性时都调用代码时,它很有用.通常,当每次引用存储属性时都需要重新计算计算属性(例如,从其他可能是私有的存储属性重新计算)时,您会执行此操作.

The computed property’s block, however, is called each time you reference the variable. It’s useful when you want the code to be called every time you reference the computed property. Generally you do this when the computed property needs to be recalculated every time you reference the stored property (e.g. recalculated from other, possibly private, stored properties).

在这种情况下,您无疑需要存储属性(第一个示例),而不是计算属性(第二个示例).每次引用变量时,您大概都不想要一个新的推送行为对象.

In this case, you undoubtedly want the stored property (the first example), not the computed property (the second example). You presumably don't want a new push behavior object each time you reference the variable.

顺便说一下,在你的第一个例子中,你在内部引用了它被延迟实例化.如果你想要这种行为,你必须使用 lazy 关键字:

By the way, in your first example, you internally reference to it being instantiated lazily. If you want that behavior, you must use the lazy keyword:

lazy var pushBehavior: UIPushBehavior = {
    let behavior = UIPushBehavior()
    behavior.setAngle(50, magnitude: 50)
    return behavior
}()

然而,如果属性是static,它会自动延迟实例化.

If, however, the property is static, it is automatically instantiated lazily.

这篇关于计算属性和使用闭包设置的属性之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆