0

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:

  1. On the console I see this: fatal error: Can't unwrap Optional.None (lldb)
  2. 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...

José María
  • 2,835
  • 5
  • 27
  • 42

1 Answers1

0

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()
}
}
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • I don't know what you mean by "the type system gets confused". The only problem in OP's code is that array/objectForKey returns nil if the key is not set, so you have to check for that situation (as in your code). - (In this particular case it would also make sense to return an empty array if the key does not exist.) – Martin R Jul 05 '14 at 10:07
  • OK, then using that how do I append the money value to the array? Cause if I do myArray.append it does not seem to work (Inmutable value of type 'Array'only has mutating members named 'append') – José María Jul 05 '14 at 11:06
  • @MartinR no, the swift runtime or compiler often messes up - for me I got a runtime error I386 INVALIDOP or something -- I blame it on swift being beta. I HAVE to go via the workaround of declaring the var as AnyObject! and then casting it – Daij-Djan Jul 05 '14 at 11:06
  • @MartinR I do get that quite often anyways :D – Daij-Djan Jul 05 '14 at 11:08
  • see if nil or not. if nil create it, if not nil make a mutableCopy – Daij-Djan Jul 05 '14 at 11:09
  • @Daij-Djan Could you please elaborate a bit more? – José María Jul 05 '14 at 11:37