Search code examples
swift3swift4macos-high-sierraxcode9.1

Cannot subscript a value of type '[String : String]' with an index of type 'NSUserInterfaceItemIdentifier'


In my project (MacOS, Swift 4), I get this error: "Cannot subscript a value of type '[String : String]' with an index of type 'NSUserInterfaceItemIdentifier'" when I'm trying to set the NSTableViewDataSource. It worked just fine in Swift 3, but when I updated the project to Swift 4, it stopped working.

So what I'm trying to do, is to show the "tableViewData" in the "tableView" by using cell id.

This is my code:

    import Cocoa

    class ViewController: NSViewController {

        @IBOutlet weak var tableView:NSTableView!

        let tableViewData = [["picID":"default","nameID":"default","amount":"1","address":"default"],["picID":"default","nameID":"default","amount":"1","address":"default"]]

        override func viewDidLoad() {
            super.viewDidLoad()
            self.tableView.delegate = self as? NSTableViewDelegate
            self.tableView.dataSource = self


        }
    }

    extension ViewController:NSTableViewDataSource{
        func numberOfRows(in tableView: NSTableView) -> Int {
            return tableViewData.count
        }

        func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
            return tableViewData[row][(tableColumn?.identifier)!] // This is where the error appears 
        }
    }

Any idea what has been changed in Swift 4?


Solution

  • NSUserInterfaceItemIdentifier is a struct type. You should call .rawValue to get the underlying value:

    tableViewData[row][(tableColumn?.identifier.rawValue)!]