如何在Swift中使用多个键过滤Nsdictionary

  • 本文关键字:过滤 Nsdictionary Swift swift
  • 更新时间 :
  • 英文 :

{
    address = "street1";
    country = India;
    state = uttarpradesh;
}
{
    address = "street2";
    country = US;
    state = New York;
}

这是我的字典

我正在使用搜索栏作为过滤器

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
     // Put your key in predicate that is "Name"

    let filteredArray = MyDict.filter { ($0["address"] as! String).range(of: searchText!,  ($0["country"] as! String).range(of: searchText!, ($0["state"] as! String).range(of: searchText!, options: [.diacriticInsensitive, .caseInsensitive]) != nil }
    print ("array = (filteredArray)")
    if(filteredArray.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.TableView.reloadData()
}

而不是此

let filteredArray = MyDict.filter { ($0["address"] as! String).range(of: searchText!,  ($0["country"] as! String).range(of: searchText!, ($0["state"] as! String).range(of: searchText!, options: [.diacriticInsensitive, .caseInsensitive]) != nil }

使用 &&要求两个bool表达式为true或 ||以做一个true的表达式。

因此,要检查地址或(||)该县是否具有文字,请使用

let filteredArray = MyDict.filter { 
   ($0["address"] as! String).range(of: searchText!) != nil ||  
   ($0["country"] as! String).range(of: searchText!) != nil 
}

您可以使用更多||和子表达添加更多检查

在您显示的字典中,我尚不清楚我的国家是一个弦。您需要将其转换为串字符串的国家名称。

在您的示例中推测 MyDictNSDictionary的数组:

let filteredArray = MyDict.filter {
    for key in $0.allKeys {
        if let string = $0[key] as? String,
            string.contains(searchText) {
            return true 
        }
    }
    return false
}
searchActive = filteredArray.count > 0

此外,您可能会发现熟悉Swift指南的基本知识

非常有用

最新更新