您好我想在标签中显示用户的分数。我告诉它只要对象为零就要做什么,但由于某种原因,当标签加载时它仍然有错误。我该如何解决这个问题?
这是我的代码:
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!")
}
由于
答案 0 :(得分:1)
使用可选绑定检查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!"
}
或者您可以使用 nil-coalescing operator ??
来创建score
字符串:
let score = (PFUser.currentUser()?["score"] as? String) ?? "Create or Go to a Spot!"
self.SpotScore.text = "Spot Score: " + score