Timm Kent
Timm Kent

Reputation: 1268

Good programming style with optionals

I want to read an enum parameter from NSUserdefaults. In case there is nothing set in Userdefaults I want it to default to a certain value. Is there a better way (more elegant) to do this than what I did here with the "if let" statement? And as this is a Singleton I want to access the value in other parts of my code using

if GameState.learnLevel == Level.low {..}

how would I do that?

class GameState {

var learnLevel:Level
enum Level:Int {
   case low = 1,medium,high
}

class var sharedInstance: GameState {
    return _SomeManagerSharedInstance
}

init(){

    // load games state
    let learnLevel = Level(rawValue: NSUserDefaults.standardUserDefaults().integerForKey("learnLevel"))

    if let learnLevel1 = learnLevel {self.learnLevel = learnLevel1} else {self.learnLevel = Level.low}

}

Upvotes: 2

Views: 66

Answers (1)

Michał Ciuba
Michał Ciuba

Reputation: 7944

Use nil coalescing operator ??:

    let learnLevel = Level(rawValue: NSUserDefaults.standardUserDefaults().integerForKey("learnLevel"))        
    self.learnLevel = learnLevel ?? Level.low

Upvotes: 3

Related Questions