簡體   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