confile confile - 2 years ago 115
Swift Question

Swift equivalent of lazy Property getter

What is the Swift equivalent of the following expression:

@property (strong, nonatomic) UIView *topView;

- (UIView *)topView {

Is it the following:

var topView: UIView {
get {

If the former is true, is there a way to define an external getter?

Answer Source

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;

This lazy property getter is easy to achieve in Swift:

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download