gpt4 book ai didi

ios - 使用 UISearchController Swift 4 搜索多个结构体数组

转载 作者:行者123 更新时间:2023-11-29 05:57:34 24 4
gpt4 key购买 nike

我有两个数据数组,我想搜索它们,但不知道如何使用 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()
}

希望这对某人有意义!谢谢!

最佳答案

如果它们都有名称和价格,您可以执行类似的操作,对于最后一部分,您可以向上转换另一个数组并将它们组合成一个大数组:

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())
}

关于ios - 使用 UISearchController Swift 4 搜索多个结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com