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'
and
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.