2014-10-27 47 views
0

我一直在使用Xcode 6 Playground中的內容過濾器系統在Swift中,這個想法是,如果我輸入一個帶有多個單詞的字符串(例如:「Apple Oranges Bananas「),函數將把這個字符串分隔成一個數組,然後用這些單詞循環遍歷數據庫,並且如果匹配的話應該返回true。所以我的函數返回true,如果我把整個單詞,但是當我把一個單一的字母返回false ...我使用「RangeOfString」行,所以它應該通過逐字符字符,但我不知道..真的難倒。內容過濾器功能不能正常工作...找不到bug

這裏是代碼..

// 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") 

任何幫助將非常感激!

回答