问题
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.
回答1:
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
}
回答2:
You have to initialize the enum using rawValue
:
self.selectedFormula = CalculationFormula(rawValue: userDefaults.objectForKey("selectedFormula") as! Int)
回答3:
You should save your value as:
userDefaults.setInteger(yourValue, forKey: "yourKey")
Load your value as:
userDefaults.integerForKey("yourKey") // Returns 0 if the value is nil.
来源:https://stackoverflow.com/questions/37368830/how-do-i-convert-a-userdefault-value-from-anyobject-to-an-int-so-i-can-save-it