Добавление SearchBar в uitableview сталкивается с ошибкой в ​​процессе фильтрации - PullRequest
1 голос
/ 01 октября 2019

Я следую учебному пособию о том, как добавить панель поиска для табличного представления пользовательского интерфейса в свой быстрый проект, я перешел по этой ссылке https://www.youtube.com/watch?v=XtiamBbL5QU и застрял в половине кода. В этой строке моего проекта

 self.countries.filter { (Country:String) -> Bool in
            <#code#>
        }

У меня есть эта ошибка String' is not convertible to 'HistoryViewController.Country HistoryViewController - это имя моего контроллера табличного представления. и единственное, что отличается в моем проекте с учебником, это то, что у меня есть массив стран, в который входят строки словарей. Я собираюсь опубликовать мои другие части кодов здесь

import UIKit

class HistoryViewController: UITableViewController , UISearchResultsUpdating {


    var searchController : UISearchController!
    var resultsController = UITableViewController()


    var myPlistArray: [String] = []

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        return 115 //or whatever you need
    }

    struct Country : Decodable {
        let flagEmoji, Abb, countryName, pName : String

        private enum CointryKeys : String, CodingKey { case flagEmoji, Abb, countryName, pName }
    }

    var countries = [Country]()

    func updateSearchResults(for searchController: UISearchController) {
        //Filter through currencies

        self.countries.filter { (Country:String) -> Bool in
            <#code#>
        }

        // Update the results Table View

    }




    override func viewDidLoad() {
        super.viewDidLoad()


        self.searchController = UISearchController(searchResultsController: self.resultsController)
        self.tableView.tableHeaderView = self.searchController.searchBar
        self.searchController.searchResultsUpdater = self

        let url = Bundle.main.url(forResource: "Curr", withExtension: "plist")!
        let data = try! Data(contentsOf: url)


        do {

            countries = try PropertyListDecoder().decode([Country].self, from: data)
        } catch {
            // Handle error
            print(error)
        }
        print(countries)
        print("countries.count:", countries.count)


    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return countries.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("hiiii")

        let cell = tableView.dequeueReusableCell(withIdentifier: "historyCell", for: indexPath) as! TableViewCellforHistory

        // Configure the cell...


        cell.lblCellHistory.text = countries[indexPath.row].countryName
        cell.lblEmoji.text = countries[indexPath.row].flagEmoji
        cell.lblCurrencyName.text = countries[indexPath.row].pName

        return cell
    }
 }

Ответы [ 2 ]

1 голос
/ 01 октября 2019

У вас нет словаря, но есть массив стран, поэтому закрытие фильтра должно выглядеть примерно так:

let result  = countries.filter { $0.countryName.starts(with: searchStr) }

или

let result  = countries.filter { $0.countryName == searchStr) }

В зависимости от того, как вы хотите фильтровать,Если вы хотите сделать поиск нечувствительным к регистру, то вызовите lowercased() для свойства и строки поиска

let result  = countries.filter { $0.countryName.lowercased().starts(with: searchStr.lowercased()) }
1 голос
/ 01 октября 2019

Измените закрытие filter, как показано ниже, поскольку countries - это массив Country, но вы рассматриваете его как String (делая Country: String),

 self.countries.filter { country -> Bool in
      return country.countryName == "Pakistan"
 }

или

 self.countries.filter { (country: Country) -> Bool in
      return country.countryName == "Pakistan"
 }

Или просто:

self.countries.filter { $0.countryName == "Pakistan" }

Изменить

Чтобы получить список стран names (т. Е. [String]),Вы должны использовать map для отфильтрованного результата, как показано ниже,

let filteredCountryNames = self.countries.filter { (country: Country) -> Bool in
          return country.countryName == "Pakistan"
     }.map { $0.countryName }
...