问题
In the app I'm developing, I need to create an array that will store values of a variable (money, which is a double and changes when the user inputs a different value). So the idea was to create an array variable from a NSUSerDefaults key:
var moneyArray:Array = NSUserDefaults.standardUserDefaults().arrayForKey("MoneyArray")
Then I needed to append the value so:
moneyArray.append(money)
And now I would save the array again:
NSUserDefaults.standardUserDefaults().setObject(moneyArray,forKey:"MoneyArray")
In the middle, I was printing the array to see the values. But I can't execute this code. Whenever I run the app, this happens:
- On the console I see this: fatal error: Can't unwrap Optional.None (lldb)
- Highlighted on my code, I see this: Thread 1: EXC_BAD_INSTRUCTION...
And I don't know what I'm doing wrong or where should I look for more info about this...
回答1:
I think the type system gets confused by arrayForKey because really it still returns AnyObject!
I always hav a wrapper property:
var myArray : Array<Double>! {
get {
if let myArray: AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("myArray") {
println("\(myArray)")
return myArray as Array<Double>!
}
return nil
}
set {
println(myArray)
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "myArray")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
来源:https://stackoverflow.com/questions/24584972/swift-create-an-array-of-double-values-and-save-it-to-nsuserdefaults