相当于懒惰的属性获取器的Swift [英] Swift equivalent of lazy Property getter
本文介绍了相当于懒惰的属性获取器的Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下表达式的Swift等效项是什么:
What is the Swift equivalent of the following expression:
@property (strong, nonatomic) UIView *topView;
- (UIView *)topView {
...
}
是以下内容:
var topView: UIView {
get {
...
}
}
如果前者为真,是否有办法定义外部吸气剂?
If the former is true, is there a way to define an external getter?
推荐答案
我认为您要问的是如何实现类似于以下内容的东西:
I think what you're asking is how to implement something similar to the following:
@property (nonatomic, strong) UIView *topView
- (UIView *)topView {
if (_topView == nil) {
_topView = //...
// configure _topView...
}
return _topView;
}
这个懒惰的属性获取器很容易在Swift中实现:
This lazy property getter is easy to achieve in Swift:
lazy var topView: UIView = {
let view = //...
// configure view...
return view
}()
这将导致一个只读变量,该变量仅在首次访问时才初始化.您发布的Swift代码是计算所得的只读属性,每次访问该属性都会对其进行评估.
This results in a read-only variable that is initialised only when first accessed. The Swift code you posted is a computed read-only property which is evaluated every time it is accessed.
这篇关于相当于懒惰的属性获取器的Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文