【发布时间】:2015-03-18 01:59:08
【问题描述】:
惰性属性的基本概念如下。
// 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 堆栈是使用 Lazy Properties 设置的。但是,代码不是我以前见过的,希望有人能帮助我理解语法。
// 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 堆栈末尾的 () 和 check 属性末尾的 : () 让我感到困惑。
保重,
乔恩
【问题讨论】: