[英]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. Xcode 更新后出现“AnyObject 不是 NSArray 的子类型”错误。 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.你根本不应该在 Swift
AnyObject
和NSArray
用于值类型。 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 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
}
}
And declare noteItems
as并将
noteItems
声明为
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.您将
storednoteItems
键入为AnyObject
,但随后您试图对其调用count
,并尝试为其添加下标。 It looks like what you actually want is for storednoteItems
to be an array, so why not type it as that?看起来您真正想要的是将
storednoteItems
设为一个数组,那么为什么不这样输入呢? Instead of as AnyObject?
而不是
as AnyObject?
, just use as? [String]
,只是
as? [String]
as? [String]
to type storednoteItems
to be an array of strings. as? [String]
将storednoteItems
键入为字符串数组。 Then get rid of the : AnyObject
declaration on the type and your array will behave as you'd expect.然后去掉类型上的
: AnyObject
声明,您的数组将按照您的预期运行。
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.使用
foreach
循环非常有效,只需将循环替换为以下循环即可。
for item in storednoteItems{
noteItems.append(storednoteItems[i])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.