我一直在使用Swift中的XCode 6 Playground中的内容过滤系统,并且想法是如果我输入一个包含多个单词的字符串(例如:“Apple Oranges Bananas”),该函数会将此字符串分隔为然后使用任何这些单词在数组中循环,如果匹配则返回true。所以我的函数返回true如果我把整个单词但当我放一个字母时返回false ...我使用了“RangeOfString”行,所以它应该逐个字符地通过单词,但我不知道..真的难倒
这是代码..
// Playground - noun: a place where people can play
import UIKit
class Person {
var name = ""
var age = 0
init(name: String, age:Int) {
self.name = name
self.age = age
}
}
var filteredItems = [Person]()
var items = [ Person(name: "Anders", age: 23), Person(name: "Alice", age: 56), Person(name: "Amanda", age: 88)]
items.append(Person(name: "Andrew", age: 23))
func filterContentForSearchText(searchText : String) -> Bool
{
var filtered = false
//Filter the array using the filter method
filteredItems = items.filter({( search : Person) -> Bool in
let stringMatch = queryValidator(searchText, search.name)
let intMatch = queryValidator(searchText, String(search.age))
filtered = (stringMatch != false || intMatch != false)
return (stringMatch != false || intMatch != false)
})
return filtered
}
func queryValidator(search : String, database : String) -> Bool
{
//Function that splits search query into multiple querys
let query = search.uppercaseString.componentsSeparatedByString(" ")
var queryFound = false
for(var i = 0; i < query.count; i++)
{
let match = query[i].uppercaseString.rangeOfString(database.uppercaseString)
if(match != nil)
{
queryFound = true
}
}
return queryFound
}
filterContentForSearchText("a")
任何帮助都会非常感激!!
答案 0 :(得分:0)
string.rangeOfString不执行前缀匹配。因此,如果您使用&#34; a&#34;进行搜索,则您的阵列中的任何人都不会使用名称&#34; a&#34;。如果要进行前缀匹配,请尝试使用String.hasPrefix(如https://developer.apple.com/library/mac/Documentation/General/Reference/SwiftStandardLibraryReference/index.html中所述)。