string - 将字符串转换为整数,以便可以将数值相加

标签 string swift parse-platform integer

您好,在我正在创建的应用程序中,我有一个积分系统,每次用户完成特定任务时,他们都会获得 100 分。我的问题是,由于该对象是一个字符串,因此数字值实际上是相加在一起的,因此 100 + 100 结果为 100100。我该如何解决这个问题?由于某种原因 .toInt 不起作用。

这是我的代码:

 // Give the User Points

    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! String

                let points = (("100".toInt())! + (score.toInt())!)

                foundUser!["score"] = points


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

                    if succeeded {

                        println("score added to user")

                    }


                })

            }

        })

    }

另一个问题是,当用户第一次开始获取积分时,Parse.com 中的列为零,因此没有任何内容可以添加 100 分,因此应用程序崩溃。我该怎么办?

谢谢

最佳答案

这适用于您的场景吗?

if let  score = foundUser!["score"] as? String {
    if let points = score.toInt() {
        points += 100
        foundUser!["score"] = "\(points)"
    }
}

关于string - 将字符串转换为整数,以便可以将数值相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31998546/

相关文章:

swift - 我如何更好地构建这些数据?

parse-platform - 如何将 Parse.Promise 与其他形式的 Promise 混合使用,例如Bluebird/ES6 原生 promise ?

parse-platform - Parse.com Arduino Yun SDK 快速入门教程不​​起作用

php - 如何将这个json数组保存到MYSQL数据库

java - String.split() 将保留原始的 char 数组在里面

ios - Swift 的惰性变量

ios - 尝试在点击 Google map 标记时运行函数

string - 在 Swift 中生成随机字母数字字符串

algorithm - 字符串平铺算法

ios - 点击播放按钮闪烁停止