Search code examples
iosarraysswiftswift2ambiguous

Ambiguous use of subscript using [indexPath.section][indexPath.row]


After I updated to Xcode 7.2 an error popped up saying "Ambiguous use of subscript" at the following:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

      /*ERROR - Ambiguous use of subscript*/
      cell.textLabel?.text = self.tvArray[indexPath.section][indexPath.row] as? String 

      //..... more code
}

Can anyone tell me what I've done wrong when implementing tvArray?

The setup:

var tvArray = []

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)

  //..... more code
  tvArray = [["Airing Today", "On The Air", "Most Popular", "Top Rated"], ["Action & Adventure", "Animation", "Comedy", "Documentary", "Drama", "Family", "Kids", "Mystery", "News", "Reality", "Sci-Fic & Fantasy", "Soap", "Talk", "War & Politics", "Western"]]
  //..... more code
}

Solution

  • tvArray = [] without explicit type is inferred to [AnyObject].

    Tell the compiler the proper type of the array: An Array containing arrays of String.
    Then it knows that the array can be subscripted by index.

    var tvArray = Array<[String]>()
    

    or

    var tvArray = [[String]]()
    

    Additional benefit: The type casting in cellForRowAtIndexPath is not needed

    cell.textLabel?.text = self.tvArray[indexPath.section][indexPath.row]