通过闭包初始化属性 [英] Initializing property via closure
本文介绍了通过闭包初始化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我观察到人们有时使用闭包来初始化属性。例如而不是
I've observed that people sometimes using closures to initialize properties. e.g. instead of
lazy var test1: String = String("a string")
他们使用
lazy var test2: String = { String("a string") }()
使用闭包来实现的好处/便利是什么?
What is the benefit/convenience in using closure to initialize property?
推荐答案
这两个函数执行相同的工作。当需要额外的代码来配置属性对象时,闭包初始化非常方便。例如:
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)
}()
这篇关于通过闭包初始化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文