《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/