【问题标题】:'subscript(_:)' is unavailable: cannot subscript String with an Int (Swift 5)'subscript(_:)' 不可用:不能用 Int 下标 String (Swift 5)
【发布时间】:2020-01-30 07:16:12
【问题描述】:

我在这里只找到了一个答案。我的问题是我没有使用Characters,除非String 是一个字符集合。我试着把它变成String 即;

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

但我得到同样的错误无法将类型“字符”的值分配给类型“字符串?”

这是我的手机:

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"]

}

这是我的控制器:

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
    }

【问题讨论】:

  • array[String] 所以 array[indexPath.section]String。添加[indexPath.row] 部分就像尝试做"hello"[5]。这就是你的错误的原因。您试图将 array 视为二维数组,但它只是一维的。
  • 那么我应该如何计算它们,数组中的字符串数量?
  • @rmaddy 我尝试了一个范围[..<index],但我得到一个额外的错误二元运算符'.. - 这是有道理的,因为 indexPath 不是 Int 或 String。

标签: swift uitableview character subscript custom-sections


【解决方案1】:

您应该只使用row 获得indexPath 所需的name,如下所示,

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]

【讨论】:

  • 我的索引超出范围。运算符也不工作:(
  • 没关系。我必须在我的numberOfSections 中返回 1 部分,并在我的 numberOfRows 中返回 sections.count。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 2014-10-09
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多