Adrian Adrian - 1 year ago 65
Swift Question

Add a cell only if certain conditions are met

So i have an array of struct where i add data from my json. There are different types of data in the same array.

struct PersonData {
let name: String
let age: String
let sex : String

What i want to do is to implement a pickerView that will reload the table view depending on what the user choose. Lets say i have 2 picker views where the user can choose sex and age.

So if he chose all males with 17 years old i want to show only that on the table view.

I can already get the count on the array but i can't return nil on the

I wanted to do something like this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

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

if(option == 0) //All persons. Default option
{ = dataArray[indexPath.row].name
return cell

if(dataArray[indexPath.row].age == agePickerOption || dataArray[indexPath.row].sex == sexPickerOption )
{ = dataArray[indexPath.row].name
return cell

return nil


I know i cant return nil since he is expecting a UITableViewCell but its possible to only increment the indexPath if certain conditions are met?

Or i need to add the cell and delete it right after? This doesn't sounds right.

Answer Source

I would have two data arrays:

allDataArray - all elements

filteredDataArray - elements that comply to your filter

If you use the filteredArray as a DataSource you dont have to put that logic in the cellForRow Method.

Instead, use the picker delegate methods to filter your allDataArray and put it on the filteredDataArray.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download