【问题标题】:Avoid duplicates in array in swift 3在swift 3中避免数组中的重复
【发布时间】:2016-10-05 16:50:31
【问题描述】:

我正在尝试从数组内的 tableView 中的选定行中获取数据。我会将选定的行附加到数组中,这确实很好用。不幸的是,当我取消选择该行并再次选择它时,它会再次附加它。我需要编写一些逻辑来从数组中删除取消选择的行。

有人知道我该怎么做吗?

这是我选择一行时的代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell
        selectedCell?.contentView.backgroundColor = UIColor(red: 84.0 / 255, green: 199.0 / 255, blue: 252.0 / 255, alpha: 1)

        rowSelected+=1

        if rowSelected >= 1 {
            nextBtn.isEnabled = true
            nextBtn.backgroundColor = UIColor(red: 84.0 / 255, green: 199.0 / 255, blue: 252.0 / 255, alpha: 1)
        }

        let exercisesSelected = selectedCell?.exerciseNameLbl.text

        exerisenames.append(exercisesSelected!)

        print(exerisenames)

    }

这里是取消选择行的代码:

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell
        selectedCell?.textLabel?.textColor = UIColor.darkGray

        rowSelected-=1

        if rowSelected == 0 {
            nextBtn.isEnabled = false
            nextBtn.backgroundColor = UIColor.darkGray
            nextBtn.setTitle("Choose an exercise", for: UIControlState.disabled)
        }

        let exercisesDeselected = selectedCell?.exerciseNameLbl.text


        if exerisenames.contains(exercisesDeselected!) {
            print("exercise already in the row and has to be deleted before going further")
        }

        print(exerisenames)

    }

两者都将引用我在顶部创建的数组:executivenames

【问题讨论】:

  • exerisenames.removeObject(exercisesDeselected)
  • 它给了我[String]没有成员removeObject的错误
  • 为什么不用集合代替数组?
  • @almas 因为 OP 可能希望保留订单。
  • 如果您说出您使用的 Swift 版本可能会有所帮助。

标签: ios arrays swift uitableview


【解决方案1】:

快速浏览一下文档,您可能想要类似

if let index = exercisenames.index(of: exercisesDeselected) {
    exercisenames.remove(at: index)
}

但我也认为@almas 关于有序集的建议可能很好。

【讨论】:

  • 但是在这种情况下什么是索引?我的 tableView 中有多行。如果我先选择第 3 行然后删除第 2 行,反之亦然?
  • @KevinVugts index 是元素的位置,即在这种情况下为existsDeselected。如果确实存在,则将其删除。但是在这样做之后,数组内容会被移动,因此另一个元素将存储在该位置
  • 这正是代码所说的——在您的阵列上调用index(of:) 的结果。这将返回数组中的索引。你可能想看看 Swift 文档,里面都有。
  • 它给了我错误:无法使用以下类型的参数列表调用索引:字符串
  • 检查您的代码,因为它可以删除字符串。您是否包含of:
猜你喜欢
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多