2015-01-19 4 views
3

게으른 속성의 기본 개념은 다음과 같습니다.스위프트 게으른 속성에 대한 자세한 내용

// 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)! 
}() 

테이크 관리,

존 사과의 예에서

답변

4

는 사과 암시 적 변수 유형을 지정 해당 코드 자체의 NSManagedObjectModel

첫 번째 예에서는 해당 변수의 유형을 지정하지 않고 값을 반환하지 않습니다 (할당 또는 초기화). 따라서 컴파일러는 형식을 암시 적으로 지정해야하며 형식을 초기화해야한다고 불평합니다.

기본적인 아이디어는 형식을 암시 적으로 지정해야하며 초기화해야한다는 것입니다 (println을 작성하고 초기화하지 않아도됩니다.) 따라서 시나리오에서는 그 특정 값을 갖지 않습니다 . 게으른 변수 당신이 필요로하는 그래서 그것이 빈 폐쇄와 같은 유형의 지정하고 당신이 그것을 초기화하는

또 다른 예를 들어, 체크 7을 할당합니다 다음 :..

lazy var check : Int = { 
    println("This is your check") 
    return 7 
}() 
+0

최고 감사하는 이유. 폐쇄 마지막에()를 추가해야합니까? Apple은 귀하의 예처럼 그것을 수행합니다. – jonthornham

+0

@jonthornham : 기능을 만들기 위해 (익명의 functio n은 게으른 변수의 값을 계산하고 반환합니다) –

관련 문제