如何在 Swift 中保存要解析的整数

How to save an Integer to Parse in Swift

我正在尝试将 integer 值保存到 Parse.com,但出现错误。我将 Parse class 中的对象设置为 Number.

这是我的代码:

  if let currentUser = PFUser.currentUser() {

        currentUser.fetchIfNeededInBackgroundWithBlock({ (foundUser: PFObject?, error: NSError?) -> Void in

            // Get and update score

            if foundUser != nil {

                let score = foundUser!["score"] as! Int

                let points = 100 + score

                foundUser!["score"] = points

                foundUser?.saveInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in

                    if succeeded {

                        println("score added to user")
                    }
                })

            }

        })

    }

有人可以帮忙吗?

谢谢

我认为您应该这样将 foundUser!["score"] 转换为 Int

let score = foundUser?["score"].integerValue

编辑

if let currentUser = PFUser.currentUser() {

        currentUser.fetchIfNeededInBackgroundWithBlock({ (foundUser: PFObject?, error: NSError?) -> Void in

            // Get and update score

            if foundUser != nil {

                if let score = foundUser?["score"].integerValue {
                    let points = 100 + score

                    foundUser!["score"] = points

                    foundUser?.saveInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in

                        if succeeded {

                            println("score added to user")
                        }
                    })
                }
            }

        })

    }

希望对您有所帮助。

发生此错误是因为您将 nil 转换为 Int。

我认为有效:

if let currentUser = PFUser.currentUser() {

    currentUser.fetchIfNeededInBackgroundWithBlock({ (foundUser: PFObject?, error: NSError?) -> Void in

        // Get and update score

        if let foundUser = foundUser {
            if let score = foundUser["score"] as? Int {
                foundUser["score"] = 100 + score
            } else {
                foundUser["score"] = 0
            }

            foundUser.saveInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in

                if succeeded {

                    println("score added to user")
                }
            })

        }
    })
}