简体   繁体   中英

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. i keep on getting "UInt8 is not convertible to Int8" this is the code

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:

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.

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 .

I got here some examples for how to save NSUserDefaults and how to retrieve it. What you are seeing here is how I save text from an UITextField and how I save a UISwith. You will also see how I retrieve this information out of my 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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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