sha*_*eet 4 nsdictionary uitableview ios swift
我正在尝试显示类别的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]();
Run Code Online (Sandbox Code Playgroud)
这里只是一个附加到数组并将"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;
}
Run Code Online (Sandbox Code Playgroud)
然后...
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
}
Run Code Online (Sandbox Code Playgroud)
当我尝试将变量设置为等于给定indexpath.row中数组内部的项时,我收到错误:
'不能下标'[(String)]类型的值?' 索引类型为'Int'
我真的很困惑,为什么这不起作用,所以任何帮助都会很棒.
您sectionArray是可选的,因此您可以通过以下方式访问它的对象:
var itemInArray = sectionArray?[indexPath.row]
Run Code Online (Sandbox Code Playgroud)
你的输出将是:
Optional("Asian Food")
Optional("Mexican Food")
Optional("Fast Food")
Run Code Online (Sandbox Code Playgroud)
如果您不想要可选,那么您可以这样解开:
var itemInArray = sectionArray![indexPath.row]
Run Code Online (Sandbox Code Playgroud)
你的输出将是:
Asian Food
Mexican Food
Fast Food
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14446 次 |
| 最近记录: |