Trip Phillips
Trip Phillips

Reputation: 440

fatal error: when my PFUser object is unwrapped

Hi I am trying to show the user's score in a label. I have told it what to do whenever the object is nil but for some reason it still has an error when the label loads. How do I fix this issue?

Here is my code:

    let score: AnyObject? = PFUser.currentUser()!.objectForKey("score")

        self.SpotScore.text = ("Spot Score: " + (score! as! String))
        if score == nil{

            self.SpotScore.text = ("Spot Score: Create or Go to a Spot!")
        }

Thanks

Upvotes: 0

Views: 26

Answers (1)

vacawama
vacawama

Reputation: 154603

Use optional binding to check for nil:

if let score = PFUser.currentUser()?["score"] as? String {
    self.SpotScore.text = "Spot Score: \(score)"
} else {
    self.SpotScore.text = "Spot Score: Create or Go to a Spot!"
}

or you could use the nil-coalescing operator ?? to create the score string:

let score = (PFUser.currentUser()?["score"] as? String) ?? "Create or Go to a Spot!"
self.SpotScore.text = "Spot Score: " + score

Upvotes: 1

Related Questions