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

时间:2020-05-16 19:03:53

标签: ios swift

我收到此错误:

无法将类型“ 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
    }

}

2 个答案:

答案 0 :(得分:0)

目标是一个数组。

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

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

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

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

Goals.remove(at: indexPath.row)

答案 1 :(得分:-1)

您需要删除数组元素而不是String中的SubString,请替换显示错误的行:

Goals.remove(at: indexPath.row)