【问题标题】:Cannot convert value of type 'Int' to expected argument type 'String.Index'无法将“Int”类型的值转换为预期的参数类型“String.Index”
【发布时间】:2020-05-16 19:03:53
【问题描述】:

我收到此错误:

无法将“Int”类型的值转换为预期的参数类型“String.Index”

在线Goals[0].remove(at: indexPath.row)。我该如何解决?

这是我的代码:

import UIKit

class GoalsViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var Goals: [String] = ["goal 1", "goal 2", "goal 3"]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }
}

extension GoalsViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         if indexPath.section == 0 {
             Goals[0].remove(at: indexPath.row)
             tableView.reloadData()
         }
     }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Goals.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "GoalCell_1", for: indexPath)
        cell.textLabel?.text = Goals[indexPath.row]
        return cell
    }

}

【问题讨论】:

  • 你到底想在这里实现什么?
  • 我试图在单击单元格后将其删除,然后最终将其移动到新的表格视图

标签: ios swift


【解决方案1】:

Goals 是一个数组。

var Goals: [String] = ["goal 1", "goal 2", "goal 3"]

在这里你选择数组'[0]'的第一个元素并尝试从中'.remove',但它是一个字符串

Goals[0].remove(at: indexPath.row)

如果要从目标数组中删除字符串:

Goals.remove(at: indexPath.row)

【讨论】:

    【解决方案2】:

    您需要删除数组元素而不是字符串中的子字符串,将显示错误的行替换为:

    Goals.remove(at: indexPath.row)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 2017-01-09
      • 2017-02-08
      相关资源
      最近更新 更多