Search code examples
swiftuitableviewswift3uisearchbarsearchbar

Can anyone tell me why my filtered array is empty?


I have a table view and a search bar added to it (programmatically). I want to show the filtered results, so I've created an array(called: todoTitle) which contains titles for my todo activities (I have a separate object for them and one of its properties is title). I use updateSearchResults method and inside of it I use a filter method to return right todos. In order to check that the arrays aren't empty, I write code inside of that function to print the todos inside of each array. Here is my code inside of updateSearchResults(for:) function

    //filtering through todos' titles
    filteredTodos = self.todosTitle.filter({ (title: String) -> Bool in
        if title.lowercased().contains((self.searchController.searchBar.text?.lowercased())!) {
            return true
        } else {
            print ("S \(todosTitle)")
            print ("t \(title)")
            print (filteredTodos)

            return false

        }
    })
    //updating the results TableView
    self.resultsController.tableView.reloadData()

}

``

todosTitle array isn't empty, so I don't understand why my filteredTodos is empty. Does anyone have any ideas why this could happen?


Solution

  • You only need to check for if the todo item title contains the search text. Here's a simplified example that I tested with an array of strings and a search text string. Perhaps separate out your assignment of the search text to ensure you're getting the string you expect from the searchBar.text

    let todosTitle = ["One", "Two", "Three"]
    let searchText = "t"
    
    //filtering through todos' titles
    let filteredTodos = todosTitle.filter({ (title: String) -> Bool in
        return title.lowercased().contains(searchText.lowercased())
    })
    
    print(filteredTodos)  //["Two", "Three"]