Andrew Aquino Andrew Aquino - 10 months ago 43
Swift Question

Content filter function not working... Can't find bug

I've been messing with a content filter system in XCode 6 Playground in Swift and the idea is that if I input a string with multiple words (Ex: "Apple Oranges Bananas"), the function will separate this string into an array then cycle through the database with any of these words and should return true if there is a match. So my function returns true if I put a whole word but returns false when I put a single letter... I used the "RangeOfString" line so it should go through the word character by character but i don't know.. Really stumped.

Here is the code..

// Playground - noun: a place where people can play

import UIKit

class Person {
var name = ""
var age = 0

init(name: String, age:Int) { = 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,
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


Any help would be really appreciated!!

tng tng
Answer Source

string.rangeOfString does not do a prefix match. So if you search with "a", you don't have any people in your array with a name that is "a". If you want to do prefix match, try using String.hasPrefix (as described in