0

I'm trying to manage a variable like this:

var isFinished: Bool {
    get {
      return NSUserDefaults.standardUserDefaults().boolForKey("isFinished")
    }
    set {
      NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: "isFinished")
      NSUserDefaults.standardUserDefaults().synchronize()
    }
  }

This works, however, I'm trying to make it more safe by using an if let when getting:

var isFinished: Bool {
    get {
      if let isFinished = NSUserDefaults.standardUserDefaults().boolForKey("isFinished") as? Bool {
        return isFinished
      }
    }
    set {
      NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: "isFinished")
      NSUserDefaults.standardUserDefaults().synchronize()
    }
  }

This will give a yellow error though: "Conditional cast from 'Bool' to 'Bool' always succeeds."

Alright then:

if let isFinished = NSUserDefaults.standardUserDefaults().boolForKey("isFinished") {
  return isFinished
}

Now it's worse: "Initializer for conditional binding must have Optional type, not 'Bool'"

What's the correct way of handling this?

nontomatic
  • 2,003
  • 2
  • 24
  • 38

2 Answers2

3

Your primary approach is fine.

boolForKey of NSUserDefaults doesn't return an optional therefore any optional binding attempt is meaningless.

func boolForKey(_ aKey: String) -> Bool

If a Boolean value is associated with the specified key, that value is returned. If the key was not found, this method returns NO.

vadian
  • 274,689
  • 30
  • 353
  • 361
1

You need to write in this way :-

if let isFinished : Bool = NSUserDefaults.standardUserDefaults().boolForKey("isFinished") 
{
      return isFinished
}

Hope this will help you :)

N.Raval
  • 549
  • 3
  • 11
  • This will raise the *Initializer for conditional binding must have Optional type, not 'Bool'* error – vadian Feb 27 '16 at 11:29
  • Thanks for your answer, N.Raval, I've accepted the other answer since it seems to be Apple's recommendation and people, like me, may not know the way this is actually handled. Because your answer does work indeed, I gave it an upvote. – nontomatic Feb 27 '16 at 11:50
  • @nontomatic Thank you :) – N.Raval Feb 27 '16 at 11:51