惰性属性的基本概念如下。
// I create a function that performs a complex task.
func getDailyBonus() -> Int
{
println("Performing a complex task and making a connection online")
return random()
}
//I set define a property to be lazy and only instantiate it when it is called. I set the property equal to the function with the complex task
class Employee
{
// Properties
lazy var bonus = getDailyBonus()
}
我开始使用 CoreData 开发一个新项目,并注意到 Core Data 堆栈是使用惰性属性设置的。但是,代码不是我以前见过的东西,希望有人能帮助我理解语法。
// From Apple
lazy var managedObjectModel: NSManagedObjectModel =
{
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("FLO_Cycling_1_1_1", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
Apple 使用 { 自定义代码 }() 语法。我的第一个想法是,他们在定义惰性属性时只是简单地使用了一个闭包,以消除首先创建函数的需要。然后我尝试了以下。
// I tried to define a lazy property that was not an object like so.
lazy var check = {
println("This is your check")
}()
编译器提示并建议以下修复。
// I do not understand the need for the ": ()" after check
lazy var check: () = {
println("This is your check")
}()
谁能帮我理解语法? CoreData 堆栈末尾的 () 和检查属性末尾的 : () 让我感到困惑。
保重,
乔恩
最佳答案
在苹果的例子中,
lazy var managedObjectModel: NSManagedObjectModel =
{
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("FLO_Cycling_1_1_1", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
可以看到,apple隐式指定了变量类型:
lazy var managedObjectModel: NSManagedObjectModel
并从该代码本身返回一个 NSManagedObjectModel
。
在您的第一个示例中,您没有指定该变量的类型,也没有返回任何值(分配或初始化)。所以编译器会提示你需要隐式指定一个类型并且需要初始化它。
基本思想是,你需要隐式指定它的类型,还需要初始化它(只写一个 println,不会初始化它。所以在你的场景中。你对那个特定的惰性没有任何值(value)变量。因此您需要将它的类型指定为一个空闭包,并用它来初始化它。
另一个例子,下面将把 7 赋值给支票:
lazy var check : Int = {
println("This is your check")
return 7
}()
关于ios - 更详细的 Swift 惰性属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035204/