想看看是否有人了解为什么在一个项目中会产生 "ambigious use of subscript" 错误,而在 swift 中会产生另一个错误

Wanted to see if anyone has any insight to why an "ambigious use of subscript" error is created in one project vs. another in swift

所以根据下面的项目教程expandableCells,使用 NSMutableArray 的子脚本是可行的。 (我在 xcode 中自己打开了项目并且没有出现错误)

当我尝试在我自己的项目中使用此工作流程时,到处都是 "ambiguous use of subscript" 错误。这与上一个问题

中提出的问题相同

我的问题是,为什么 appcoda 提供的项目可以在 xcode 中运行,但当尝试在新项目中使用类似的工作流程时,类似的代码却不起作用。现在请注意,问题似乎是 swift 如何处理 NSMutableArray 因为当我将代码重写为 swift 数组和字典时,一切正常,除了没有简单的方法将 plist 转换为 swift数组.

我的plist格式和教程一样:Array, Array, Dictionary

这是我看到错误的片段

var cellDescriptors: NSMutableArray!

func loadSections() {

    let path: String = NSBundle.mainBundle().pathForResource("NewCells", ofType: "plist")!
    cellDescriptors = NSMutableArray(contentsOfFile: path)
    getIndicesOfVisibleRows()
    tblExpandable.reloadData()
}

func getIndicesOfVisibleRows() {
    visibleRowsPerSection.removeAll()

    for currentSectionCells in cellDescriptors {
        var visibleRows = [Int]()

        for row in 0...((currentSectionCells ).count - 1) {
**ERROR HERE==>** if currentSectionCells[row]["isVisible"] as! Bool == true {
                visibleRows.append(row)
            }
        }

        visibleRowsPerSection.append(visibleRows)

        print("visibleRows \(self.visibleRowsPerSection)")
    }
}

正如您链接到的答案中所解释的那样,Foundation 容器(NSArrayNSDictionary 等)是未类型化的。所以,currentSelectionCells[row] returns AnyObject。 Swift 不会让您下标 AnyObject 因为它可能不是容器。它实际上可以是任何东西。

如果您仔细查看 AppCoda 文章中的代码

for row in 0...((currentSectionCells ).count - 1) {

他们有

for row in 0...((currentSectionCells as! [[String: AnyObject]]).count - 1) {

他们已经将 currentSelectCells 桥接到一个包含 String:AnyObject 的 Swift 字典的 Swift 数组,所以当他们稍后说 currentSelectionCells[row] 时,他们会得到一个字典[String:AnyObject]。这个可订阅的,Swift很高兴。

因此, 是一种将 plist 转换为 Swift 数组的简单方法。通常最好尽早将 Foundation 容器转换为 Swift 容器,因为这样您就可以获得成员类型化的优势。如果他们将 loadCellDescriptors 实现为类似以下内容会更好:

var cellDescriptors: [[String:AnyObject]]!

func loadCellDescriptors() {
    if let path = NSBundle.mainBundle().pathForResource("CellDescriptor", ofType: "plist") {
        let plist = NSMutableArray(contentsOfFile: path)
        cellDescriptors = plist as! [[String:AnyObject]]
        getIndicesOfVisibleRows()
        tblExpandable.reloadData()
    }
}