ios - 无法使用类型为 '[(String)]?' 的索引下标类型为 'Int' 的值

标签 ios swift uitableview nsdictionary

我正在尝试显示类别的表格 View ,每个类别都有自己的一组类别。

例如,主要类别是食品、娱乐、休闲,在 tableview 的食品部分中,墨西哥食品、亚洲食品等显示在该部分下。

但是,我遇到了这个错误:

Cannot subscript a value of type '[(String)]?' with an index of type '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: 中数组内的项目时出现错误

'Cannot subscript a value of type '[(String)]?' with an index of type '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

关于ios - 无法使用类型为 '[(String)]?' 的索引下标类型为 'Int' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31422262/

相关文章:

ios - 如何获得 UITableViewCell 移动开始和结束的通知?

objective-c - 你如何从 Swift 调用 Objective-C 可变参数方法?

ios - UITableViewCell 的动态维度可以,但是如果为空如何隐藏它们?

ios - fatal error ..从另一个类访问变量时

ios - 自定义 UITableViewCell 对触摸没有反应

ios - swift ios : different errors for similar data . 。很奇怪

iphone - iOS 中检查字符串是否是字符串列表之一的最有效方法是什么?

ios - 如何以编程方式获取 iOS 崩溃日志?

ios - 更改 'More' 选项卡的导航栏色调颜色

swift - 将类型存储在变量中以便以后像类型一样使用