使用 UISearchController Swift 4 搜索多个结构数组
Posted
技术标签:
【中文标题】使用 UISearchController Swift 4 搜索多个结构数组【英文标题】:Searching Multiple Struct Arrays With UISearchController Swift 4 【发布时间】:2019-03-05 02:46:00 【问题描述】:我有两个要搜索的数据数组,但不知道如何使用 UISearchController 进行搜索
struct Fish
var name: String
var price: Int
var fishArray: [Fish] = [ Fish(name: "Bass", price: 1),
Fish(name: "Pike", price: 2),
Fish(name: "Carp", price: 3),
Fish(name: "Bluegill", price: 4),
Fish(name: "Catfish", price: 5)]
struct Weapons
var name: String
var price: Int
var weaponsArray: [Weapons] = [ Weapons(name: "Sword", price: 1),
Weapons(name: "Knife", price: 2),
Weapons(name: "Gun", price: 3),
Weapons(name: "Poison", price: 4),
Weapons(name: "Hammer", price: 5)]
搜索发生在这里。仅搜索武器非常有用,但是以后如何添加鱼和其他多个数组。
func filterContentForSearchText(_ searchText: String, scope: String = "All")
filteredData = weaponsArray.filter(( weapon : Weapons) -> Bool in
return weapon.name.lowercased().contains(searchText.lowercased())
)
mainTableView.reloadData()
希望这对某人有意义!谢谢!
【问题讨论】:
如果两个结构的属性相似,那你为什么没有一个结构呢? 我实际上不得不问自己同样的问题......但我的例子中同时拥有名称和价格并不是他们唯一的东西......他们每个人都有其他几个独特的属性.话虽如此,我仍然可以让一个结构为我正在做的事情工作。谢谢! 【参考方案1】:如果它们都有名称和价格,你可以这样做,对于最后一部分,你可以向上转换另一个数组并将它们组合成一个大数组:
protocol Item
var name: String get set
var price: Int get set
struct Fish: Item
var name: String
var price: Int
var fishArray: [Fish] = [ Fish(name: "Bass", price: 1),
Fish(name: "Pike", price: 2),
Fish(name: "Carp", price: 3),
Fish(name: "Bluegill", price: 4),
Fish(name: "Catfish", price: 5)]
struct Weapons: Item
var name: String
var price: Int
var weaponsArray: [Weapons] = [ Weapons(name: "Sword", price: 1),
Weapons(name: "Knife", price: 2),
Weapons(name: "Gun", price: 3),
Weapons(name: "Poison", price: 4),
Weapons(name: "Hammer", price: 5)]
var items: [Item] = (fishArray as [Item]) + (weaponsArray as [Item])
items.filter (item) -> Bool in
return item.name.lowercased().contains("C".lowercased())
【讨论】:
这看起来很有希望!我从未使用过协议,但似乎这可能是一个不错的选择!看看这是否有效!谢谢!以上是关于使用 UISearchController Swift 4 搜索多个结构数组的主要内容,如果未能解决你的问题,请参考以下文章