根据 NSPredicate SWIFT 过滤结构数组

Filter a struct array according to a NSPredicate SWIFT

我有一个 UITableView 和一个 UISearchController。我想根据 UISearchBar.textNSPredicate 过滤我的数据数组(名为:allGames)。

我的代码只过滤这样一个字符串数组:

func updateSearchResults(for searchController: UISearchController) {

    filteredGames.removeAll(keepingCapacity: false)

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    let array = (allGames).filtered(using: searchPredicate)

    filteredGames = array as! [String]

    self.tableView.reloadData()
}

在这里我可以过滤我的数组。但是如果我创建这个结构:

struct Games {

    var name: String?
    var type: String?
    var image: UIImage?
}

如何根据游戏名称和类型过滤数组?预先感谢您的帮助。

假设 allGames 是一个数组 [Games] – 顺便说一句,结构应该以单数形式命名 Game – 我强烈建议使用原生 Swift filter 函数

let searchText = searchController.searchBar.text!
let fileredGames = allGames.filter { [=10=].name?.range(of: searchText, options: [.caseInsensitive]) != nil 
                                  || [=10=].type?.range(of: searchText, options: [.caseInsensitive]) != nil }

同时考虑将结构中的 typename 声明为非可选。