Swift 相当于惰性 属性 getter

Swift equivalent of lazy Property getter

以下表达式的 Swift 等价物是什么:

@property (strong, nonatomic) UIView *topView;

- (UIView *)topView {
...
}

是否是以下:

var topView: UIView {
  get {
    ...
  }
}

如果是前者,有没有办法定义一个外部的getter?

认为你问的是如何实现类似于以下的东西:

@property (nonatomic, strong) UIView *topView

- (UIView *)topView {
    if (_topView == nil) {
        _topView = //...
        // configure _topView...
    }
    return _topView;
}

这个偷懒属性getter在Swift中很容易实现:

lazy var topView: UIView = {
    let view = //...
    // configure view...
    return view
}()

这导致只读变量仅在首次访问时初始化。您发布的 Swift 代码是计算的只读代码 属性,每次访问时都会对其进行评估。