下面的代码在两年前曾经工作正常。
它在Xcode更新后有"AnyObject不是NSArray的子类型"错误。 谁能帮我修复它?
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)
}
}
}
在 Swift 中,你根本不应该对值类型使用AnyObject
和NSArray
。并且不应注释编译器可以推断的类型。
UserDefaults
有一个专用的方法array(forKey
来获取数组。 您的代码可以简化为
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
}
}
并声明noteItems
为
var noteItems = [String]()
如果指定类型,则不需要循环中的任何类型转换。
在较新版本中更新,请尝试使用此..
if let storednoteItems = UserDefaults.standard.object(forKey: "noteItems") as? [String] {
var noteItems = [String]()
for i in 0 ..< storednoteItems.count{
noteItems.append(storednoteItems[i])
}
}
使用foreach
循环非常有效,只需将循环替换为下面的循环即可。
for item in storednoteItems{
noteItems.append(storednoteItems[i])
}
您正在键入storednoteItems
作为AnyObject
,但随后您尝试调用count
,并尝试对其进行下标。看起来您真正想要的是storednoteItems
是一个数组,那么为什么不这样键入呢?不要as AnyObject?
,只需使用as? [String]
键入storednoteItems
作为字符串数组。然后删除类型上的: AnyObject
声明,数组将按预期运行。