swift - 如果全局属性总是延迟计算,而局部属性从不延迟计算,那么lazy修饰符会修改什么?

标签 swift properties lazy-evaluation

《Swift 编程语言 (Swift 2.1)》第 248 页的注释解释了以下内容:

Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier.

Local constants and variables are never computed lazily.

摘自:Apple Inc.“Swift 编程语言 (Swift 2.1)”。 https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11

除了全局属性和局部值之外,还有其他类型的常量或变量会受到 lazy 修饰符的影响吗?

最佳答案

所提供的摘录中的“局部常量和变量”指的是局部作用域常量和变量,如函数的局部变量。它们不引用对象的属性,如果用lazy关键字标记它们,则对象的属性可以是惰性的。

//global, declared outside of a class/struct
//error is "Lazy is only valid for members of a struct or class
lazy var label: UILabel = {
    var tempLabel: UILabel = UILabel()
    tempLabel.text = "hi"
    return tempLabel
}()

class SomeClass : NSObject {
    //non-lazy instance property
    var x = 3

    //lazy instance property
    lazy var label: UILabel = {
        var tempLabel: UILabel = UILabel()
        tempLabel.text = "hi"
        return tempLabel
    }()


    func doStuff() {
        //error is "Lazy is only valid for members of a struct or class
        lazy var label: UILabel = {
            var tempLabel: UILabel = UILabel()
            tempLabel.text = "hi"
            return tempLabel
        }()
    }
}

关于swift - 如果全局属性总是延迟计算,而局部属性从不延迟计算,那么lazy修饰符会修改什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36043376/

相关文章:

ios - Swift:如何通过按导航栏按钮访问选项卡栏项目

c# - PropertyInfo.GetValue(myObject, null).GetType() 返回 "Object reference not set to an instance of an object."

ios - swift 中的惰性函数评估

swift - handleOpenURL,第二个参数(sourceApplication)使用什么值?

ios - swift 3 : URL Image makes UITableView scroll slow issue

javascript 对象属性引用

haskell - 了解涉及 GHCi let 绑定(bind)时 thunk 的不同行为

ios - UICollectionView 单元格的 "Lazy Drawing"

swift - 在swift中解析get_video_info(YouTube信息数据)

java - 如何在 spring boot 中从 message_ru_RU.properties 加载俄语(西里尔字母,utf-8)文本?