Nil check inside getter method in swift?

I have an array in my controller. It should be allocated only if it is equal to zero, otherwise it should return the existing value.

Objective equivalent of C:

- (NSArray*)states{
     if(!_states)
     {
         _states = //read files from json and assigned to array
     }
     return _states;
}

I must strive for this quickly. I tried with the property saved, but could not achieve this.

What is the best way to achieve this?

+4
source share
3 answers

It could be something like this:

class Whatever {
    private(set) var _states: [AnyObject]?
    var states: [AnyObject] {
        get{
            if let st = _states {
                return st
            }
            else {
                // Read from file
                _states = ....
                return _states!
            }
        }
    }
}

SWIFT , , private(set) var _states: [AnyObject]?, , _states , . readonly, _states, st, nil .
SWIFTY-, :

class Whatever {
    lazy var states: [AnyObject] = {
        return array read from file
    }()
}

, , , , , . , .

+2

. _states, . , _states , _states.

+2

we can also use this in Swift 3.0.

private var _designContentViewController: DesignContentViewController?

var designContentViewController: DesignContentViewController? {
    get {
        if _designContentViewController == nil {
            _designContentViewController = DesignContentViewController()
            self.view.addSubview((_designContentViewController?.view)!)
            _designContentViewController?.view.isHidden = true
            _designContentViewController?.view.backgroundColor = UIColor.white
        }
        return _designContentViewController

    }
    set {
        _designContentViewController = newValue
    }
}
+2
source

All Articles