繁体   English   中英

Swift - Xcode 9.4.1 - AnyObject 不是 NSArray 的子类型

[英]Swift - Xcode 9.4.1 - AnyObject is not a subtype of NSArray

两年前,以下代码曾经可以正常工作。

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 AnyObjectNSArray用于值类型。 并且您不应该注释编译器可以推断的类型。

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

如果您指定类型,则循环和循环中的任何类型转换都不是必需的。

您将storednoteItems键入为AnyObject ,但随后您试图对其调用count ,并尝试为其添加下标。 看起来您真正想要的是将storednoteItems设为一个数组,那么为什么不这样输入呢? 而不是as AnyObject? ,只是as? [String] as? [String]storednoteItems键入为字符串数组。 然后去掉类型上的: AnyObject声明,您的数组将按照您的预期运行。

在较新版本中更新尝试使用此..

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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