Swift 中的惰性变量计算不止一次吗? [英] Are lazy vars in Swift computed more than once?

查看:29
本文介绍了Swift 中的惰性变量计算不止一次吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 中的惰性变量计算不止一次吗?我的印象是他们取代了:

Are lazy vars in Swift computed more than once? I was under the impression that they replaced the:

if (instanceVariable) {
    return instanceVariable;
}

// set up variable that has not been initialized

Objective-C 的范式(惰性实例化).

Paradigm from Objective-C (lazy instantiation).

他们就是这样做的吗?基本上只在应用程序第一次请求变量时调用一次,然后只返回计算的内容?

Is that what they do? Basically only called once the first time the app asks for the variable, then just returns what was calculated?

还是每次都像普通的计算属性一样被调用?

Or does it get called each time like a normal computed property?

我问的原因是因为我基本上想要一个可以访问其他实例变量的 Swift 计算属性.假设我有一个名为fullName"的变量,它只是连接 firstNamelastName.我将如何在 Swift 中做到这一点?似乎惰性变量是唯一的方法,因为在普通计算变量(非惰性)中,我无法访问其他实例变量.

The reason I ask is because I basically want a computed property in Swift that can access other instance variables. Say I have a variable called "fullName" and it just concatenates firstName and lastName. How would I do that in Swift? It seems like lazy vars are the only way to go, as in normal computed vars (non-lazy) I can't access other instance variables.

所以基本上:

Swift 中的惰性变量是否被多次调用?如果是这样,我如何创建一个可以访问实例变量的计算变量?如果不是,如果出于性能原因我只想计算一次变量,我该怎么做?

Do lazy vars in Swift get called more than once? If so, how do I create a computed variable that can access instance variables? If not, if I only want a variable to be computed once for performance reasons, how do I do this?

推荐答案

lazy var 仅在您第一次使用它们时计算一次.之后,它们就像一个普通的变量.

lazy vars are only calculated once, the first time you use them. After that, they're just like a normal variable.

这很容易在操场上测试:

This is easy to test in a playground:

class LazyExample {
    var firstName = "John"
    var lastName = "Smith"
    lazy var lazyFullName : String = {
        [unowned self] in
        return "\(self.firstName) \(self.lastName)"
    }()
}

let lazyInstance = LazyExample()

println(lazyInstance.lazyFullName)
// John Smith

lazyInstance.firstName = "Jane"

println(lazyInstance.lazyFullName)
// John Smith

lazyInstance.lazyFullName = "???"

println(lazyInstance.lazyFullName)
// ???

如果您想稍后重新计算它,请使用计算属性(带有支持变量,如果它很昂贵) - 就像您在 Objective-C 中所做的一样.

If you'll want to recalculate it later, use a computed property (with a backing variable, if it's expensive) - just like you did in Objective-C.

这篇关于Swift 中的惰性变量计算不止一次吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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