Editing an Array Saved to User Defaults SWIFT

312 Views Asked by At

I have been trying to read data from an Array that is saved to User Defaults but the object types cause conflicts.

if NSUserDefaults.standardUserDefaults().valueForKey("data")==nil{
        let arrya : Array = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry",
            "Clementine", "Coconut", "Cranberry", "Fig", "Grape", "Grapefruit",
            "Kiwi fruit", "Lemon", "Lime", "Lychee", "Mandarine", "Mango",
            "Melon", "Nectarine", "Olive", "Orange", "Papaya", "Peach",
            "Pear", "Pineapple", "Raspberry", "Strawberry"]
        NSUserDefaults.standardUserDefaults().setObject(arrya, forKey: "data")
}

var data = NSUserDefaults.standardUserDefaults().objectForKey("data")

I am using objectForKey not valueForKey because of the answer to this question.

This question would answer my question, however... well... it doesn't. I still have issues. For example:

Trying

data.count

returns an error:

Value of type 'AnyObject?' not unwrapped; did you mean to use '!' or '?'?

Trying:

cell.textLabel?.text = data[0]

returns an error:

Could not find an overload for 'subscript' that accepts supplied arguments

Why are the types not compatible? I was hoping that what I retrieve from User Defaults is the same type as this:

["hola", "alo", "ya", "shalom", bounjour", 1, 3, "ai"]

Thanks very much for any response in advance. All are welcome and greatly appreciated!

2

There are 2 best solutions below

0
On BEST ANSWER

cast to array

var data = NSUserDefaults.standardUserDefaults().objectForKey("data") as! Array<String>

better use if let to check if casting failed

0
On

The value returned from objectForKey(_:) is AnyObject? (because NSUserDefaults can store any type of object), but you are trying to treat the return value like an Array. It may well be an array, but the compiler doesn't know that, so you need to tell it.

If you are sure that the returned value will be an array of strings, you can force case it when you initialise your data variable:

var data = NSUserDefaults.standardUserDefaults().objectForKey("data") as! [String]

The compiler will now know that data is of type [String], and use subscripting and properties like count on it.