Computed variable return self if exists or new instance if nil

694 views Asked by At

If I have a ScoreModel for my app that I need to pass to the next UIViewController. It may not exist and thus not passed to this new UIViewController. If this is the case I would like to have it create a new instance of the Model. This won't work (endless loop) but it will give the idea of what i'm trying to create:

var scoreModel : ScoreModel! {
    get {
        if self.scoreModel == nil {
            return ScoreModel()
        } else {
            return self.scoreModel
        }
    }
    set {
        self.scoreModel = newValue
    }
}

How can I check if the current version of scoreModel == nil without getting in a loop?

3

There are 3 answers

0
PJayRushton On BEST ANSWER

What if, instead of trying to mess around with custom getters/setters, you just made your scoreModel property optional (better convention anyway) and when you want to pass it to the next view controller you check if its nil. Something like this:

var scoreModel: ScoreModel?
let nextViewController = UIViewController()
nextViewController.scoreModel = scoreModel ?? ScoreModel()
1
vadian On

Actually you are talking about a lazy initialized variable

lazy var scoreModel = ScoreModel()

The initializer is called when the variable is accessed the first time.

1
matsoftware On

You can use a lazy var like this:

class Test {


   lazy var scoreModel: ScoreModel = {
        return ScoreModel()
    }()

}

let test = Test()
test.scoreModel = ScoreModel()