类型'Any'没有下标成员 - NSMutableArray

seu*_*ear 1 arrays casting type-erasure swift

我们导入了一个过时的项目,它促使我们将它转​​换为Swift 3.作为对Swift知之甚少的人,我们在修复错误方面遇到了困难. 在此图像中可以找到错误

import Foundation

class CellDescriptorHelper {

let itemKey = "Items"
let isExpandableKey = "isExpandable"
let isExpandedKey = "isExpanded"
let isVisibleKey = "isVisible"
let titleKey = "title"
let locationKey = "location"
let descriptionKey = "description"
let imageURLKey = "imageURL"
let typeKey = "type"
let cellIdentifierKey = "cellIdentifier"
let additionalRowsKey = "additionalRows"

fileprivate var cellDescriptors: NSMutableArray!
fileprivate var cellsToDisplay: NSMutableArray!

func getCellDescriptors(_ type: String) -> NSMutableArray {

    loadCellDescriptors(type)
    return cellDescriptors;
}

func loadCellDescriptors(_ type: String) {

    cellDescriptors = PlistManager.sharedInstance.getValueForKey(itemKey)! as! NSMutableArray

    for i in 0..<(cellDescriptors[0] as AnyObject).count-1 {

        let cellType = cellDescriptors[0][i][typeKey] as! String //creates error
        if(cellType != type) {
            cellDescriptors[0][i].setValue(false, forKey:  isVisibleKey) //creates error
        }
    }
}
} 
Run Code Online (Sandbox Code Playgroud)

Jac*_*ing 6

您收到此错误的原因是因为数组中对象的类型对编译器不明确.

这是因为NSArrays没有具体打字. NSArray基本上是Array<Any>或的Objective-C桥梁[Any].

让我带您完成代码......

let cellType = cellDescriptors[0][i][typeKey] as! String

编译器知道cellDescriptorsNSArray因为它被声明为上述之一.NSArrays可以下标获取给定索引的值,就像您正在使用的那样cellDescriptors[0].Any如上所述,这给出的值是类型,因此当您尝试再次下标时cellDescriptors[0][i],您将收到错误.碰巧,您可以将该Any对象强制转换为数组,然后您就可以执行下标,如下所示:

if let newArr = (cellDescriptors[0] as? [Any])[i] { }

然而,这真的不是一个很好的方法,你最终处理了一堆讨厌的选项.

一个更好的方法是具体你的声明cellDescriptors.我不知道你的类型结构是怎样的,但从事物的外观来看,它是一系列字典数组(yuck).因此,在原始形式中,您的声明应该var cellDescriptors = [[[AnyHashable:Any]]]()像您现在一样下标.

这就是说,你所拥有的代码很乱,我会考虑改变你对对象进行建模的方式,使它更有用.

  • 这行`var cellDescriptors = [[[:]]]`给我一个错误:`不能调用非函数类型的值'[Array <Dictionary <AnyHashable,Any >>]'`删除`()`修复它或*也许*做像[[[Any:cellDesciptors]]]()`这样的东西是你原来的意思? (2认同)