0

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?

Michael
  • 32,527
  • 49
  • 210
  • 370
  • `Computed Properties`? – Peter M Mar 12 '15 at 20:33
  • @PeterM what did you mean? – Michael Mar 12 '15 at 20:34
  • Perhaps this will help: (http://stackoverflow.com/questions/24025340/property-getters-and-setters) – Jason Cidras Mar 12 '15 at 20:37
  • Based on the title of your question, I would answer that the `Swift equivalent of Property getter` is a `Computed Property` (https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html). Now it may be that I just don't understand your actual question. – Peter M Mar 12 '15 at 20:37

1 Answers1

8

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.

Stuart
  • 36,683
  • 19
  • 101
  • 139
  • Even in the lazy example you posted I need a helper variable right? Or can I set topView directly? – Michael Mar 13 '15 at 09:09
  • 2
    @confile No, the lazy example is self contained. The `topView` variable is initialised with the return value of the closure following the '`=`'. If the initialisation can be done on one line, there is no need for the closure, for example: `lazy var topView = UIView(frame: CGRect.zeroRect)`. I'd strongly recommend reading the ['Properties' chapter of The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html). – Stuart Mar 13 '15 at 09:22
  • 3
    Answer mentions that "This results in a read-only variable that is initialised once when first accessed, and cannot be changed thereafter". As far as I can tell, a `lazy` variable _can_ be re-assigned after instantiation. – sabajt May 03 '16 at 02:21
  • @sabajt You’re right, thank you. I’m not sure whether this is behaviour that has changed since Swift 1.0, or whether I was just making a false assumption (I feel like I’d tried mutating lazy vars before and failed, but I can’t find evidence that it has ever changed). Either way, I’ve updated the answer. – Stuart May 03 '16 at 09:00