게으른 속성의 기본 개념은 다음과 같습니다.스위프트 게으른 속성에 대한 자세한 내용
// 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은 {custom code}() 구문을 사용합니다. 첫 번째 생각은 게으른 속성을 정의 할 때 클로저를 사용하여 함수를 먼저 만들지 않아도된다는 것입니다. 그럼 나는 다음을 시도했다.
// 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() 속성의 끝에있는 :()은 나를 혼란스럽게합니다.
lazy var managedObjectModel: NSManagedObjectModel
과 반환 : 당신은 그것을 볼 수 있습니다
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은 귀하의 예처럼 그것을 수행합니다. – jonthornham
@jonthornham : 기능을 만들기 위해 (익명의 functio n은 게으른 변수의 값을 계산하고 반환합니다) –