简体   繁体   English

使用NSUserDefaults保存分数:UInt8不能转换为Int8

[英]Saving score with NSUserDefaults: UInt8 not convertible to Int8

I'm creating a simple game. 我正在创建一个简单的游戏。 if the player loses i want his current score to be compared with the best score saved as persistent storage as NSUserDefault. 如果玩家输了,我希望将他的当前分数与保存为NSUserDefault的最佳分数进行比较。 i keep on getting "UInt8 is not convertible to Int8" this is the code 我不断收到“ UInt8无法转换为Int8”的代码

scoreForComparingWithBestScore = UInt8(score)

            if ( scoreForComparingWithBestScore > NSUserDefaults.standardUserDefaults().objectForKey("BestScore")){

                NSUserDefaults.standardUserDefaults().objectForKey("BestScore") =     scoreForComparingWithBestScore

            }

even if i typed 即使我输入

scoreForComparingWithBestScore = Int8(score)

the error will be switched. 错误将被切换。

Thanks in advance ! 提前致谢 !

NSUserDefaults.standardUserDefaults().objectForKey("BestScore”) returns an AnyObject? . To compare this with a UInt8 (or any other Swift numeric value type – you might want to reconsider UInt8 and use Int instead unless there's a very good reason to stick with that type), you need to both unwrap the optional and also convert it to a number: NSUserDefaults.standardUserDefaults().objectForKey("BestScore”)返回AnyObject?将此与UInt8 (或任何其他Swift数值类型)进行比较–您可能要重新考虑UInt8并改用Int除非有充分的理由坚持使用使用该类型),您既需要解开可选内容,也要将其转换为数字:

if let best = NSUserDefaults.standardUserDefaults().objectForKey("BestScore")?.integerValue {
    // best will be an Int here, you can compare it to scoreForComparingWithBestScore
}
else {
    // either there was no BestScore value, or there was but it wasn't an integer
}

Alternatively, you could use the ?? 或者,您可以使用?? operator to default the best score to zero if not present (or not an integer): 运算符将不存在(或不是整数)的最佳分数默认为零:

let best = NSUserDefaults
                .standardUserDefaults()
                .objectForKey("BestScore")?
                .integerValue ?? 0

NSSUserDefaults has convenience methods to store different types of objects. NSSUserDefaults具有方便的方法来存储不同类型的对象。

In your case, rather than storing objects directly and then trying to convert them to the correct type, you could just use the convenience methods instead: 在您的情况下,可以直接使用便捷方法,而不是直接存储对象然后尝试将它们转换为正确的类型:

if let best = NSUserDefaults.standardUserDefaults().integerForKey("BestScore") {
    // best will be an Int here, you can compare it to scoreForComparingWithBestScore
}
else {
    // There was no BestScore value.
}

As long as you set the value with: 只要使用以下方式设置值:

NSUserDefaults.setInteger(best, forKey:"BestScore")

Then because of the strong type system you will know that you have put an integer into the defaults and you then only need to check if a value was set for that key instead of also worrying about whether the object was of the correct type. 然后,由于使用了强类型系统,您将知道已将整数放入默认值中,然后只需要检查是否已为该键设置了值,而不用担心该对象的类型是否正确。

This will also drive your design, as you know that the value should be an Int rather than over optimising it is an Int8 or a UInt8 . 这也将推动您的设计,因为您知道该值应该是Int而不是过度优化,它应该是Int8UInt8

I got here some examples for how to save NSUserDefaults and how to retrieve it. 我在这里得到了一些有关如何保存NSUserDefaults以及如何检索它的示例。 What you are seeing here is how I save text from an UITextField and how I save a UISwith. 您在这里看到的是如何保存UITextField中的文本以及如何保存UISwith。 You will also see how I retrieve this information out of my NSUserDefaults. 您还将看到我如何从NSUserDefaults中检索此信息。

func saveNSUserDefaults() {
    let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

    defaults.setObject(self.textFieldUrl.text + "/portal/silvertabletmenu.aspx", forKey: "url")

    defaults.setBool(switchToolbar!.on, forKey: "toolbar");
    defaults.synchronize()
}

func loadNSUserDefaults() {
    let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

    if let urlIsNotNil = defaults.objectForKey("url") as? String {
        self.textFieldUrl.text = defaults.objectForKey("url") as String
    }
    if textFieldUrl.text == "" {
        self.textFieldUrl.text = "https://thisisjustanexample.net/"
    }
    switchToolbar!.on = NSUserDefaults.standardUserDefaults().boolForKey("toolbar")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM