Jim Jim - 1 year ago 152
Swift Question

How do I convert a UserDefault value from AnyObject? to an Int so I can save it

I'm trying to learn how to work with UserDefaults and can't figure out how to store one of the values I need to store.

I have this enum:

enum CalculationFormula: Int {

case Epley

case Brzychi

case Lander

case Lombardi

case MayhewEtAl

case OConnerEtAl

and this class with a property called 'selectedFormula' that I want to be able to store as a NSUserDefaults value:

class CalculatorBrain: NSObject {

var weightLifted: Double
var repetitions: Double
var oneRepMax: Double?
var selectedFormula = CalculationFormula.Epley

init(weightLifted: Double, repetitions: Double) {
self.weightLifted = weightLifted
self.repetitions = repetitions
let userDefaults = NSUserDefaults.standardUserDefaults()
self.selectedFormula = userDefaults.objectForKey("selectedFormula") <-- error

The self.selectedFormula line gives me an error:

'Cannot assign value of type 'AnyObject?' to type 'CalculationFormula'

After much searching on SO and reading the Apple documentation I learned a lot about UserDefaults and AnyObject, but didn't find an answer.

I thought I did when I tried to cast it as an Int:

self.selectedFormula = userDefaults.objectForKey("selectedFormula") as! Int

// 'Cannot assign value of type 'Int' to type 'CalculationFormula'


self.selectedFormula = userDefaults.objectForKey("selectedFormula") as Int

// 'Cannot convert value of type 'AnyObject?' to type 'Int' in coercion

I know the preference values need to be one of these types (NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary) but I'm storing an Int so I should be good there.

I'm just stuck and would really appreciate some help. Please and thank you.

Answer Source

Since your enum

enum CalculationFormula: Int {
    case Epley, Brzychi, Lander, Lombardi, MayhewEtAl, OConnerEtAl

extends Int you can use its rawValue. So you can read/save an Int from/to NSUserDefaults.

This is how you save a formula

func saveFormula(formula: CalculationFormula) {
    NSUserDefaults.standardUserDefaults().setInteger(formula.rawValue, forKey: "selectedFormula")

And this is how you retrieve it

func loadFormula() -> CalculationFormula? {
    guard NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.contains("selectedFormula") else {
        print("No value found")
        return nil
    guard let retrievedFormula = CalculationFormula(rawValue: NSUserDefaults.standardUserDefaults().integerForKey("selectedFormula")) else {
        print("Wrong value found")
        return nil
    return retrievedFormula
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download