用于多个字典键的Swift过滤器

时间:2015-11-19 00:56:37

标签: ios swift filter

我正在为我的应用制作搜索栏。我使用filter方法获取结果。我想搜索多个键。

词典数组:

var people = [
               ["First": "John", "Last": "Doe"],
               ["First": "Steve", "Last": "Jobs"],
               ["First": "Elon", "Last": "Musk"]
             ]

我只能搜索" First"或者" Last",但不是两者都使用此代码:

searchResults = people.filter{
            var string = $0["Last"] 
            // or "First"

            string = string?.lowercaseString

            return string!.rangeOfString(searchText.lowercaseString) != nil
        }

3 个答案:

答案 0 :(得分:7)

一种方法是简单地将两个字段与搜索字符串进行比较:

var people = [
    ["First": "JohnMusk", "Last": "Doe"],
    ["First": "Steve", "Last": "Jobs"],
    ["First": "Elon", "Last": "Musk"]
]

var searchText = "Musk"

var searchResults = people.filter{
        var firstName = $0["First"]!.lowercaseString
        var lastName = $0["Last"]!.lowercaseString

       return firstName.rangeOfString(searchText.lowercaseString) != nil
              || lastName.rangeOfString(searchText.lowercaseString) != nil

}

这给了我这个结果:

2015-11-18 18:19:47.691 MyPlayground[36558:7031733] (
        {
        First = JohnMusk;
        Last = Doe;
    },
        {
        First = Elon;
        Last = Musk;
    }
)

我认为这就是你想要的。

答案 1 :(得分:5)

以下是使用NSPredicate的替代方法。 NSPredicate有一个非常强大的syntax,它可以为你做一些非常好的事情。

let firstNameQuery = "jo"
let lastNameQuery = "mus"
// [cd] means case/diacritic insensitive. %K is used to pass in key names since FIRST and LAST are reserved keywords in NSPredicate
let predicate = NSPredicate(format: "%K CONTAINS[cd] %@ OR %K CONTAINS[cd] %@", "First", firstNameQuery, "Last", lastNameQuery)
let sorted = people.filter({
    return predicate.evaluateWithObject($0)
})
// sorted would contain John Doe and Elon Musk entries

在我的示例中,我传入了对名字和姓氏的不同搜索查询,但您显然可以为两者传递相同的查询。只是展示了这种方法的力量。

答案 2 :(得分:1)

以下代码应该有效:

var people = [
        ["First": "John", "Last": "Doe"],
        ["First": "Steve", "Last": "Jobs"],
        ["First": "Elon", "Last": "Musk"]
        ]


  let searchResults = people.filter{

    var found = false
    let searText = "Elon"
    for str in $0.values {
        found = str.lowercaseString.rangeOfString(searText.lowercaseString) != nil
        if found {
            break
        }
    }
   return found
}