【问题标题】:Swift Lazy Properties in More Detail更详细的 Swift 惰性属性
【发布时间】: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 属性末尾的 : () 让我感到困惑。

保重,

乔恩

【问题讨论】:

    标签: ios swift core-data


    【解决方案1】:

    在苹果的例子中,

    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,不初始化它。所以在你的场景中。你对那个特别的懒惰没有任何价值变量。所以你需要将它的类型指定为一个空闭包,然后用它来初始化它。

    另一个例子,下面将把 7 分配给检查:

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

    【讨论】:

    • 太棒了。谢谢你。为什么一定要在闭包的末尾加上 ()? Apple 会按照您的示例进行操作。
    • @jonthornham: 让它成为一个函数(一个计算并返回惰性变量值的匿名函数)
    猜你喜欢
    • 2017-10-29
    • 2014-11-20
    • 2015-05-15
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2015-01-19
    • 1970-01-01
    相关资源
    最近更新 更多