Swift needs a way to perform initial setup on a @lazy property

Originator:cflesner
Number:rdar://17175716 Date Originated:05-Jun-2014 09:03 AM
Status:Closed Resolved:
Product:Swift Product Version:beta 1
Classification:Enhancement Reproducible:N/A
 
In Objective-C, when a property is lazily instantiated, it is common to need to perform some initial setup of the object that is going to be returned before returning it.

The only way to accomplish this same task in Swift seems to be to use a second property, which is less than ideal.

Example of using a second property:

    @lazy var _heavyView = UIView(frame: CGRectZero)

    var heavyView: UIView {
    get {
        _heavyView.layer.masksToBounds = true
        _heavyView.layer.cornerRadius = 8.0

        return _heavyView
    }
    set {
        _heavyView = newValue
    }
    }

My suggestion is that when declaring an @lazy property, you should be able to define a closure for setting up that property, like this:

    @lazy var heavyView = UIView(frame: CGRectZero) {
        heavyView.layer.masksToBounds = true
        heavyView.layer.cornerRadius = 8.0
    }

Comments

Nevermind, this capability already exists.

https://devforums.apple.com/thread/227288?start=23


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!