【问题标题】:Cannot subscript a value of type '[(String)]?' with an index of type 'Int'不能为“[(String)] 类型的值下标?”具有“Int”类型的索引
【发布时间】:2015-07-15 05:39:26
【问题描述】:

我正在尝试显示类别的表格视图,每个类别都有自己的类别集。

例如,主要类别是食物、娱乐、消遣,并且在 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”类型的索引

我真的很困惑为什么这不起作用,所以任何帮助都会很棒。

【问题讨论】:

    标签: ios swift uitableview nsdictionary


    【解决方案1】:

    您的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
    

    【讨论】:

      【解决方案2】:

      尝试下标可选数组时出现错误。最好在访问数组之前检查数组不为零。

      if let sectionArray = sectionArray {
          itemInArray = sectionArray[indexPath.row] 
      }
      

      或者如果可以在itemInArray 中设置 nil 值,您可以使用

      itemInArray = sectionArray?[indexPath.row] 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-06
        相关资源
        最近更新 更多