Search code examples
swiftuitableviewcharactersubscriptcustom-sections

'subscript(_:)' is unavailable: cannot subscript String with an Int (Swift 5)


I have only found one answer to this here. My problem is I am not using Characters except for that's what a String is - a collection of characters. I tried making this a String viz;

        let name = String(array[indexPath.section][indexPath.row])

but I get the same error Cannot assign value of type 'Character' to type 'String?'.

Here's my cell:

struct SectionStrings {
    let sections = ["Stuff", "More Stuff", "Best Stuff"]
}

struct ArrayStrings {
    let array = ["Little Stuff", "Bigger Stuff", "Biggest Stuff"]

}

struct DetailArrayStrings {
    let detailArray = ["Teeny Stuff", "Teentsie Weentsie Stuff", "Invisible Stuff"]

}

Here's my controller:

let sections = SectionStrings().sections
var array = ArrayStrings().array
let detailArray = DetailArrayStrings().detailArray

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! SettingsCell

        let name = array[indexPath.section][indexPath.row] // errors here
        cell.textLabel?.text = name
        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        cell.textLabel?.textColor = .white

        let detailName = detailArray[indexPath.section][indexPath.row] // and here
        cell.detailTextLabel?.text = detailName
        cell.detailTextLabel?.font = UIFont.systemFont(ofSize: 15)
        cell.detailTextLabel?.textColor = .white
        cell.detailTextLabel?.numberOfLines = 0

        cell.selectionStyle = .none
        cell.backgroundColor = .black

        return cell
    }

Solution

  • You should get the required name for indexPath using row only as below,

    let name = array[indexPath.row]
    cell.textLabel?.text = name
    cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 17)
    cell.textLabel?.textColor = .white
    
    let detailName = detailArray[indexPath.row]