1

The below codes used to work fine two years ago.

it has "AnyObject is not a subtype of NSArray" error after Xcode update. can anyone help me fixing it?

override func viewWillAppear(_ animated: Bool) {
    if let storednoteItems : AnyObject = UserDefaults.standard.object(forKey: "noteItems") as AnyObject? {
        noteItems = []
        for i in 0 ..< storednoteItems.count += 1 {
            // the above line getting Anyobject is not a subtype of NSArray error
            noteItems.append(storednoteItems[i] as! String)
        }
    }
}
pacification
  • 5,838
  • 4
  • 29
  • 51
Henry C
  • 13
  • 2

3 Answers3

1

You should not use AnyObject and NSArray for value types in Swift at all. And you should not annotate types the compiler can infer.

UserDefaults has a dedicated method array(forKey to get an array. Your code can be reduced to

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated) // this line is important. Don't forget to call super.
    if let storednoteItems = UserDefaults.standard.array(forKey: "noteItems") as? [String] {
        noteItems = storednoteItems
    }
}

And declare noteItems as

var noteItems = [String]()

If you specify the type the loop and any type casting in the loop is not necessary.

vadian
  • 274,689
  • 30
  • 353
  • 361
0

You're typing storednoteItems as AnyObject, but then you're trying to call count on it, as well as trying to subscript it. It looks like what you actually want is for storednoteItems to be an array, so why not type it as that? Instead of as AnyObject?, just use as? [String] to type storednoteItems to be an array of strings. Then get rid of the : AnyObject declaration on the type and your array will behave as you'd expect.

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60
0

Updated in newer version try with this ..

if let storednoteItems = UserDefaults.standard.object(forKey: "noteItems") as? [String] {
    var noteItems = [String]()
    for i in 0 ..< storednoteItems.count{
        noteItems.append(storednoteItems[i])
   }
}

Using foreach loop is much efficient, just replace your loop with below one.

for item in storednoteItems{
    noteItems.append(storednoteItems[i])
}
vaibhav
  • 4,038
  • 1
  • 21
  • 51