[英]searching for multiple keys with swift 4
我有一個簡單的應用程序,允許人們發布帖子,現在我做了一個搜索欄,以便人們可以搜索帖子,但是我想允許用戶搜索帖子的title
或帖子的location
或同時搜索帖子的標題和位置。 我的搜索是在搜索我的Firebase數據庫,但我只能將其分配為搜索title
或location
。 我有一個小問題,使其同時搜索兩個鍵
我要過濾和搜索的代碼如下所示
func filterContent(searchText:String) {
self.filteredUsers = self.userArray.filter{user in
// let title = user!["title"] as? String
let adress = user!["adress"] as? String
// return(title?.lowercased().contains(searchText.lowercased()))!
return(adress?.lowercased().contains(searchText.lowercased()))!
}
tableView.reloadData()
}
顯然,您可以看到我只能返回其中的1個搜索,您知道我可以同時返回這兩個搜索的任何方式嗎?
我也嘗試過
func filterContent(searchText:String) {
self.filteredUsers = self.userArray.filter{user in
let title = user!["title"] as? String
let adress = user!["adress"] as? String
return(adress?.lowercased().contains(searchText.lowercased()))! && (title?.lowercased().contains(searchText.lowercased()))!
}
tableView.reloadData()
}
但是代碼僅允許搜索功能起作用,例如,如果標題和地址都被命名為“ apple”,則它將起作用,但是如果title
被命名為“ apple”且adress
被命名為“ orange”,則我將搜索“ apple” “&”或“ orange”不會出現,因為&&
是布爾型,並且僅在title
的關鍵字和location
相同時才起作用。 因此,我仍然處在第一廣場,想知道如何才能使搜索過濾器同時搜索title
和address
func filterContent(searchText:String) {
self.filteredUsers = self.userArray.flatMap { (temp) -> User in
return temp
}.filter { (aUser) -> Bool in
return aUser.address?.localizedCaseInsensitiveContains(searchText) == true || aUser.title?.localizedCaseInsensitiveContains(searchText) == true
}
tableView.reloadData()
}
或者,再靠近一點。
func filterContent(searchText:String) {
self.filteredUsers = self.userArray.filter{ user in
let title = user!["title"] as? String
let address = user!["adress"] as? String
return title.localizedCaseInsensitiveContains(searchText) == true || address.localizedCaseInsensitiveContains(searchText) == true
}
tableView.reloadData()
}
我認為重要的是,您希望Flatmap刪除零個用戶,然后我喜歡直接在字符串頂部使用localizedCaseInsensitiveContains()。 希望這可以幫助。
我將用戶聲明為游樂場內的結構,以確保此方法運行良好。 快速執行此操作的最佳方法可能是創建一個領域用戶,然后使用謂詞過濾結果。 (性能)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.