闭包存储属性初始化的优点是什么? [英] What is the advantage of closure stored property Initialisation?

查看:85
本文介绍了闭包存储属性初始化的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将类的属性初始化为以下代码时,此代码有什么区别和优点/缺点:

What is the difference and the advantages/disadvantages of this code when initialising a property of a class as:

1.

let menuBar:MenuBar = {
        let mb = MenuBar()
        return mb
    }()

和:

2.

let menuBar = MenuBar()

推荐答案

这两个代码段均声明并初始化

Both of the code snippets declare and initialize stored properties, but in the first one it is initialized by closure. The reason why you should set a stored property with a closure is: there is a requirement(s) to do customization (calling a method for instance); Adapted from The Swift Programming Language (Swift 4.1) - Initialization: Setting a Default Property Value with a Closure or Function:

如果存储的属性的默认值需要一些自定义或 设置,您可以使用闭包或全局函数来提供 该属性的自定义默认值.每当一个新实例 属性所属的类型已初始化,闭包或 函数被调用,其返回值被分配为该属性的 默认值.

If a stored property’s default value requires some customization or setup, you can use a closure or global function to provide a customized default value for that property. Whenever a new instance of the type that the property belongs to is initialized, the closure or function is called, and its return value is assigned as the property’s default value.

这意味着您将能够做到:

Which means that you would be able to do:

let menuBar:MenuBar = {
    let mb = MenuBar()
    // for example, you'd need to call "doSomething" method
    // before returning the instance:
    menuBar.doSomething()
    return mb
}()

请注意,在存储的属性闭包的正文中,您将无法使用类/结构中的其他属性,因为它们尚未被初始化.示例:

Note that in the body of the stored property closure, you would be not able to able to use the other properties in your class/struct since they considered as not being initialized yet. Example:

struct MyType {
    let myString = "My String!"
    let myInt: Int = {
        let anInt = 101

        // this won't work
        print(myString)

        return anInt
    }()
}

以上代码段的结果是出现了编译时错误:

The result of the above code snippet is getting a compile-time error:

错误:实例成员"myString"不能用于类型"MyType" 打印(myString)

error: instance member 'myString' cannot be used on type 'MyType' print(myString)


此外,建议将您的财产声明为 lazy :


Furthermore at some point, it would be recommended to declare your property as lazy:

lazy var menuBar:MenuBar = {
     let mb = MenuBar()
     // for example, you'd need to call "doSomething" method
     // before returning the instance:
     menuBar.doSomething()
     return mb
 }()

表示:

惰性存储属性是其初始值不是 直到第一次使用时才进行计算.您表示一个懒惰的存储 通过在声明之前编写lazy修饰符来实现该属性.

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

这篇关于闭包存储属性初始化的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆