簡體   English   中英

不能下標[AnyObject]的值? 索引類型為Int

[英]Cannot subscript a value of [AnyObject]? with an index of type Int

這是在擴展PFQueryTableViewController的類中,我收到以下錯誤。 這些行只是PFUser
我為什么不能施展它? 有沒有解決的辦法?

錯誤是:

Cannot subscript a value of [AnyObject]? with an index of type Int

...對於這一行:

var user2 = self.objects[indexPath.row] as! PFUser

在此輸入圖像描述

問題不是演員,而是self.objects似乎是一個可選的數組: [AnyObject]?
因此,如果要通過下標訪問其中一個值,則必須先打開數組:

var user2: PFUser
if let userObject = self.objects?[indexPath.row] {
    user2 = userObject as! PFUser
} else {
    // Handle the case of `self.objects` being `nil`.
}

表達式self.objects?[indexPath.row]使用可選鏈接首先打開self.objects ,然后調用它的下標。


從Swift 2開始,您還可以使用guard語句

var user2: PFUser
guard let userObject = self.objects?[indexPath.row] else {
    // Handle the case of `self.objects` being `nil` and exit the current scope.
}
user2 = userObject as! PFUser

我遇到了同樣的問題並解決了這個問題:

let scope : String = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex] as! String

對於您的情況,您可能會:

var user2 : PFUser = self.objects![indexPath.row] as! PFUser

我的解決方法是......

  1. 如果您確定tableview只包含用戶,請嘗試將對象Array of AnyObject類型轉換為PFUser數組。 然后使用它。

只需添加一個! 對象之后的(感嘆號),如下所示:

var user2 = self.objects![indexPath.row] as! PFUser

那為我修好了:)

我在以下行中遇到了類似的問題:

array![row]

我無法理解問題的來源; 如果我換成row與一些像1的代碼編譯並沒有任何問題跑了。

然后我很樂意將其改為:

array![Int(row)]

它奏效了。 對於我的生活,我不明白為什么給數組索引-1在理論上是合法的,但是你去了。 對我來說,對於未簽名的下標是有意義的,但也許只是我; 我不得不問克里斯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM