JengGe Chao
JengGe Chao

Reputation: 160

If Let Error - Initializer for conditional binding must have Optional type, not '[NSObject : AnyObject]'

Here is my code.

    PFUser.logInWithUsernameInBackground(email, password: password) { (user: PFUser!, error: NSError!) -> Void in
        if user != nil {
            PushNotication.parsePushUserAssign()
            ProgressHUD.showSuccess("Welcome back, \(user[PF_USER_FULLNAME])!")
            self.dismissViewControllerAnimated(true, completion: nil)
        } else {
            if let info = error.userInfo {
                ProgressHUD.showError(info["error"] as! String)
            }
        }
    }

This causes error like "Initializer for conditional binding must have Optional type, not '[NSObject : AnyObject]'" Is there anybody who knows solution?

Upvotes: 4

Views: 1858

Answers (2)

Rostislav Mulyar
Rostislav Mulyar

Reputation: 15

Please update code to this:

ProgressHUD.showError(error.userInfo["error"] as! String)

Then it will work.

Upvotes: -2

Eric Aya
Eric Aya

Reputation: 70097

error.userInfo is not an Optional, it's of type [NSObject : AnyObject] as hinted by the compiler. No need to unwrap it with if let, it will never be nil.

You can replace

if let info = error.userInfo {
    ProgressHUD.showError(info["error"] as! String)
}

with

ProgressHUD.showError(error.userInfo["error"] as! String)

if you're sure the value will be a String.

Otherwise, the dictionary value should be safely unwrapped and downcast as a String. Example:

if let errorString = error.userInfo["error"] as? String {
    ProgressHUD.showError(errorString)
}

Upvotes: 4

Related Questions