我有一个tableview
,在这里我从名为PlaylistArray
的数组中加载了所有详细信息。我有一个搜索页面,用户可以从playlistArray
中搜索类型为[[String: Any]]
的。我不知道如何过滤用户在PlayListArray
到filteredArray
中给出的搜索文本。我已附上PlaylistArray
答复,以供您参考。
这是我之前尝试过滤PlaylistArray
的代码。
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (constantsList.playTypeArray.lectureArraymp3 as NSArray).filtered(using: searchPredicate)
// filtered_Array.add(array)
print(array)
我需要搜索用户提供的搜索文本,我们必须将搜索文本与title
的{{1}}标签进行比较。当两者相同时,我需要向过滤后的数组显示特定数组索引的全部细节。
PlaylistArray:
playlistArray
答案 0 :(得分:0)
这是使用filter
API的快速解决方案。在此处详细了解:https://developer.apple.com/documentation/swift/sequence/3018365-filter
let array = [["title": "Kaṭha-Bhāṣyam-41 Mantra 1-2-20", "image_url": "https://www.imaginetventures.name/swamijione/wp-content/uploads/2019/01/gitanew.png"],
["title": "Kaṭa-Bhāṣyam-41 Mantra 1-2-20", "image_url": "https://www.imaginetventures.name/swamijione/wp-content/uploads/2019/01/gitanew.png"]]
guard let searchText = searchController.searchBar.text else {return} //Or use if-let
let filteredArray = array.filter { (object) -> Bool in
guard let title = object["title"] as? String else {return false}
return title?.contains(searchText) ?? false
}
答案 1 :(得分:0)
不是使用字典数组,而是使用结构数组。创建一个结构和结构实例
//Item
struct Item {
var title: String
var imageUrl: URL
var mp3Url: URL
init?(details: [String:Any]) {
if let title = details["title"] as? String,
let imageStr = details["image_url"] as? String,
let imageUrl = URL(string: imageStr),
let mp3Str = details["mp3"] as? String,
let mp3Url = URL(string: mp3Str) {
self.title = title
self.imageUrl = imageUrl
self.mp3Url = mp3Url
} else { return nil }
}
}
然后使用title属性过滤数组。
let playlistArray = [["title": "Kaṭha-Bhāṣyam-41 Mantra 1-2-20", "image_url": "https://...", "mp3": "https://..."],
["title": "Kaṭha-Bhāṣyam-41 Mantra 1-2-20", "image_url": "https://...", "mp3": "https://..."],
["title": "Kaṭha-Bhāṣyam-41 Mantra 1-2-20", "image_url": "https://...", "mp3": "https://..."]]
let playlistArr = playlistArray.compactMap(Item.init)
print(playlistArr)
let searchText = "Kar"//searchController.searchBar.text!
let filteredArray = playlistArr.filter({ $0.title.localizedCaseInsensitiveContains(searchText) })
print(filteredArray)