gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:36:59 25 4
gpt4 key购买 nike

The Swift Programming Language (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.“The Swift Programming Language (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 - 如果全局属性总是惰性计算,而局部属性从不惰性计算,那么惰性修饰符会修改什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36043376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com