0

I am trying to search an array of nested items where enters a text and it searches both the team and user array and returns an object. I am able to search team but not able to search user nested array.

Here is my code

// Array
let searchArray = [MyTeam]()

// Search
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchArray = searchArray.filter { ($0.name.range(of: searchString, options: .caseInsensitive) != nil || ($0.users.filter{($0.name.range(of: searchString, options: .caseInsensitive) != nil }) ) }
}

// Model
struct MyTeam: Codable {
    let id: Int
    let name: String
    let users: [MyUser]
}
struct MyUser: Codable {
    let id: Int
    let name: String
}

1 Answer 1

1

Instead of using filter on the users array here

$0.users.filter {($0.name.range(of: searchString, options: .caseInsensitive) != nil }

You can use contains method which will return a Bool

$0.users.contains { $0.name.range(of: searchString, options: .caseInsensitive) != nil }

So the final function would look like this. Also I think you need to use searchText instead of searchString

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchArray = searchArray.filter { team in
        team.name.range(of: searchText, options: .caseInsensitive) != nil
            || team.users.contains { user in
                user.name.range(of: searchText, options: .caseInsensitive) != nil
            }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.