Swift 5.3中实现搜索栏多词无序全匹配的TableView过滤
Fixing Search Bar Logic for Multi-Term, Order-Independent Results
Hey there! Let's get your search functionality working correctly so it finds objects that contain all your search terms, no matter what order you type them in. Your current code has two main issues: it's checking for the entire search string as a single phrase, and you're accidentally adding the filtered results twice to filteredArray. Let's fix that step by step.
Step 1: Clarify the Core Requirement
We need to:
- Split the search input into individual keywords
- Keep only objects where every keyword appears in the
storyproperty (case-insensitive) - Ignore the order of the input keywords
Step 2: Revised Search Logic
Here's the corrected textDidChange method, with explanations for each key part:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { // Reset to full array when search text is empty guard !searchText.isEmpty else { filteredArray = Array tableView.reloadData() return } // Process the search text into clean, lowercase keywords let searchKeywords = searchText.lowercased() .components(separatedBy: .whitespacesAndNewlines) // Split on any whitespace (spaces, newlines, tabs) .filter { !$0.isEmpty } // Remove empty strings from accidental multiple spaces // Filter objects that contain ALL keywords filteredArray = Array.filter { object in let storyLowercased = object.story.lowercased() // Ensure every keyword exists in the story return searchKeywords.allSatisfy { keyword in storyLowercased.contains(keyword) } } tableView.reloadData() }
Key Improvements Breakdown:
- Robust Keyword Splitting: Using
.whitespacesAndNewlinesinstead of just spaces ensures we handle any kind of whitespace (like multiple spaces or tabs) correctly. - Cleaned Keyword List: The
filter { !$0.isEmpty }step removes empty entries that can pop up if the user types extra spaces between terms. - All Terms Match:
allSatisfyguarantees that every keyword is present in the object'sstory—this is what makes the search order-independent. For your example input "comprehension your", this will pick out objects where both words appear, regardless of their order in the story.
Testing with Your Sample Data
For your provided array, when you type "comprehension your", the filtered results will be:
Object(story:"and for free. Practicing your comprehension", age: 1800)Object(story:"your vocabulary and comprehension", age: 1500)
Which is exactly the result you're looking for!
内容的提问来源于stack exchange,提问作者Wahib
相关产品推荐
相关产品推荐

