【问题标题】:How to validate array value already exist or not如何验证数组值是否已经存在
【发布时间】:2019-03-11 17:25:56
【问题描述】:

我的任务是从iCloud 中选择files,它是url,title,etc.,然后附加到项目array。之后,我在struct 的帮助下获取每个值并在tableView 中列出。

在这里,我需要了解一件事,如何validate 用户选择的文件已经存在或不存在到我的数组中。如果存在,我不允许在他们的文件中附加alert 消息。

// Array Declaration
var items = [Item]()
var tableArray = [Item]() 

// Values appending into my array
items.append(Item(url: fileurl, title: filename, exten: fileextension, size: string))

// Tableview data load
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
    let item = tableArray[indexPath.row]

        if tableArray.count > 0 {
            cell.name_label_util.text = item.title
            cell.size_label_util.text = item.size
        }
    return cell
}

【问题讨论】:

标签: ios arrays swift


【解决方案1】:

您可以通过在现有items 数组上添加过滤器来检查Item 是否已经存在。如果结果为nil,则添加新的项目对象。

注意:我用url查看,应该是唯一的。或者用 Item modal 中的唯一键替换它。

if items.filter({ $0.url == fileurl }).first == nil {
    items.append(Item(url: fileurl, title: filename, exten: fileextension, size: string))
}

替代方案:

if items.index(where: { $0.url == fileurl }) == nil {
    items.append(Item(url: fileurl, title: filename, exten: fileextension, size: string))
}

【讨论】:

  • 这将迭代整个数组,即使它在第一个数组索引处找到元素。您应该使用 contains(where:) 而不是获取 filter 的第一个结果并检查它是否为 nil
  • 谢谢,工作得很好。顺便说一句,以上两者有什么区别? @Ankit Jayaswal
  • 我认为 filter 和 index-where 在 swift 中不遵循线性搜索,而是与 contains 相同的堆排序。
  • 包含(其中:yourPredicate)最好的一个。谢谢@Leo Dabus 和@Ankit Jayaswal。
  • @pasteldev 过滤器闭包为您提供匹配结果数组,您需要检查过滤后的数组是否为空,而 index-where 闭包提供匹配结果的索引,您可以直接使用 nil 进行检查.
【解决方案2】:

您可以使用contains(where:)通过比较类中的唯一属性来检查数组是否包含该元素。

if !items.contains(where: {$0.url == fileUrl}) {
    items.append(yourItem)
}

【讨论】:

  • 谢谢@Rakesha Shastri
猜你喜欢
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
  • 2017-05-01
  • 1970-01-01
相关资源
最近更新 更多