【问题标题】:Filter Array of structs in Swift 4.0在 Swift 4.0 中过滤结构数组
【发布时间】:2018-03-21 21:51:10
【问题描述】:

我想通过 searchBar 过滤结构数组。我知道如何过滤字符串数组,但不幸的是我无法将它应用于结构数组。这是我已经完成的:

var BaseArray: [dataStruct] = []

var filteredArray: [dataStruct] = []

BaseArray 是一个包含多个变量的结构数组。我的目标是过滤所有变量。有什么想法吗?

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == ""{
        isSearching = false
        view.endEditing(true)
        tableView.reloadData()
    }
    else{
        isSearching = true

        filteredArray = BaseArray.filter { $0.name == searchText }

        tableView.reloadData()
    }
}

【问题讨论】:

  • 我想你差不多明白了,filter 调用的花括号内的表达式可以使用 &&/|| 运算符扩展(只要它返回 true 或错误的)。这是你的意思吗?

标签: arrays swift struct


【解决方案1】:

您需要使用OR / union 运算符将阳性结果组合到过滤数组中:||

所以您的过滤器函数将如下所示:

filteredArray = BaseArray.filter { 
    $0.name == searchText
        || $0.anotherProperty == searchText
        || $0.yetAnotherProperty == searchText
}

这样,如果nameanotherPropertyyetAnotherProperty 等于您要搜索的文本,则会列出结果。

此外,您可能希望根据包含下一个的输入文本进行过滤,而不需要像您的示例中那样完全相等。在这种情况下,您的过滤功能将变为:

filteredArray = BaseArray.filter {
    $0.name.contains(searchText)
        || $0.anotherProperty.contains(searchText)
        || $0.yetAnotherProperty.contains(searchText)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多