Initializing property via closure

…衆ロ難τιáo~ 提交于 2019-12-01 08:12:28

问题


I've observed that people sometimes using closures to initialize properties. e.g. instead of

lazy var test1: String = String("a string")

they use

lazy var test2: String = { String("a string") }()

What is the benefit/convenience in using closure to initialize property?


回答1:


These two do the same work. Closure initialization comes handy when you need extra code to configure property object. E.g.:

lazy var point: CGPoint = {
    let x = ...
    let y = ...
    return CGPoint(x: x, y: y)
}()



回答2:


In general, if there is no extra work needed for the lazy variable after the initialization for it, it would be enough do declare it without the closure initialization.

For instance, for a simple string it is fair to implement:

lazy var myString = "a string"

However, when it comes to something needs more editing (setup) -like CLLocationManager for instance-, you would naturally go with the closure initialization:

lazy var locationManager: CLLocationManager = {
    var lm = CLLocationManager()

    // here is one extra thing to do:
    lm.delegate = self
    return lm
}()

As mentioned, at some point we needed to do additional step(s) after the initialization (which is lm.delegate = self in the above example).

Referring to your case, since there is nothing should happen after the initialization, both:

lazy var test1: String = String("a string")

and

lazy var test2: String = { String("a string") }()

are the same. You should go with the first one as a shorthand typing.



来源:https://stackoverflow.com/questions/51907634/initializing-property-via-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!