![](/img/trans.png)
[英]Cannot subscript a value of type '[Int : [String]]' with an index of type 'String!'
[英]Cannot subscript a value of type '[(String)]?' with an index of type 'Int'
我正在嘗試顯示類別的tableview,每個類別都有自己的類別集。
例如,主要類別是食品,娛樂,娛樂,在餐桌的食品部分,墨西哥食品,亞洲食品等顯示在該部分下。
但是,我遇到了這個錯誤:
無法下標'[(String)]類型的值?' 索引類型為'Int'
這是我的代碼:
var categoryDictionary = [String:[String]]();
var categoriesList = ["Food", "Entertainment", "Recreation", "Shopping", "Transport", "Post Office"]
var foodCategories = [String]();
var entertainmentCategories = [String]();
var recreationCategories = [String]();
var shoppingCategories = [String]();
var transportCategories = [String]();
var lodgingCategories = [String]();
var librariesCategories = [String]();
var banksCategories = [String]();
var postOfficeCategories = [String]();
這里只是一個附加到數組並將“Food”的鍵值添加到foodCategory數組的示例
func setupCategoryFood() {
var asianFood = "Asian Food"
var mexicanFood = "Mexican Food"
var fastFood = "Fast Food"
var MiddleEasternFood = "Middle Eastern Food"
foodCategories.append(asianFood);
foodCategories.append(mexicanFood);
foodCategories.append(fastFood);
foodCategories.append(MiddleEasternFood);
categoryDictionary["Food"] = foodCategories;
}
然后...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell") as! UITableViewCell;
var sectionTitle = categoriesList[indexPath.section]
var sectionArray = categoryDictionary[sectionTitle];
var itemInArray = sectionArray[indexPath.row];
return cell
}
當我嘗試將變量設置為等於給定indexpath.row中數組內部的項時,我收到錯誤:
'不能下標'[(String)]類型的值?' 索引類型為'Int'
我真的很困惑,為什么這不起作用,所以任何幫助都會很棒。
您的sectionArray
是可選的,因此您可以通過以下方式訪問它的對象:
var itemInArray = sectionArray?[indexPath.row]
你的輸出將是:
Optional("Asian Food")
Optional("Mexican Food")
Optional("Fast Food")
如果您不想要可選,那么您可以這樣解開:
var itemInArray = sectionArray![indexPath.row]
你的輸出將是:
Asian Food
Mexican Food
Fast Food
嘗試下標可選數組時出錯。 最好在訪問之前檢查數組是否為nil。
if let sectionArray = sectionArray {
itemInArray = sectionArray[indexPath.row]
}
或者,如果在itemInArray
中設置了nil值, itemInArray
可以使用
itemInArray = sectionArray?[indexPath.row]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.