Filtering nested array of struct in swift 5

Viewed 919
struct Objects {
        var sectionName : String!
        var sectionObjects : [CountryList]!
    }

var objectArray = [Objects]()

Here objectArray is my tableView data source where sectionObjects is an array of CountryList struct.

struct CountryList: Codable {
    let country_id: String?
    let country_name: String?
    let country_code:  String?
    let country_flag_url: String?

    init(countryID: String, countryName: String, countryCode:  String, countryFlagURL: String) {
        self.country_id = countryID
        self.country_name = countryName
        self.country_code = countryCode
        self.country_flag_url = countryFlagURL
    }
}

I want to filter my objectArray according to country_name.

This is what I have done in UISearchResultsUpdating.

extension CountryListViewController: UISearchResultsUpdating {
    public func updateSearchResults(for searchController: UISearchController) {
        guard let searchText = searchController.searchBar.text else {return}
        if searchText == "" {
            objectArray += objectArray
        } else {
            objectArray += objectArray

            objectArray = objectArray.filter {
                let countryListArray = $0.sectionObjects!
                for countryList in countryListArray {
                    print("cName \(String(describing: countryList.country_name))")
                    countryList.country_name!.contains(searchText)
                }
            }
        }
        self.countryListTableView.reloadData()
    }
}

And getting two errors:

Result of call to 'contains' is unused

Missing return in a closure expected to return 'Bool'

What am I missing here? Any suggestion will be highly appreciated.

Thanks in advance.

1 Answers

filter expects a bool return inside it so You need

var objectArray = [Objects]()
var filtered = [Objects]()

filtered = objectArray.filter {
  let countryListArray = $0.sectionObjects
  for countryList in countryListArray {
    print("cName \(String(describing: countryList.country_name))")
       if countryList.country_name!.contains(searchText) {
             return true 
        } 
   }
   return false
}

Or better

filtered = objectArray.filter { $0.sectionObjects.filter { $0.country_name!.contains(searchText) }.count != 0 }

Tip : use another array filtered to hold filtered data as not to overwrite main content in objectArray

Related