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

时间:2019-03-05 02:46:00

标签: ios arrays search swift4 uisearchcontroller

我有两个要搜索的数据数组,不知道如何使用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)]

搜索发生在这里。而且,仅搜索武器非常有用,但是以后如何添加Fish和其他多个数组。

func filterContentForSearchText(_ searchText: String, scope: String = "All") {
    filteredData = weaponsArray.filter({( weapon : Weapons) -> Bool in
        return weapon.name.lowercased().contains(searchText.lowercased())
    })

    mainTableView.reloadData()
}

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

1 个答案:

答案 0 :(得分:0)

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

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