简体   繁体   中英

Swift - Xcode 9.4.1 - AnyObject is not a subtype of NSArray

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)
        }
    }
}

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.

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] 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.

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])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM