BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SOLVED: Project 7 - Day 35: Filtering Petitions

Forums > 100 Days of Swift

I created the function below to step through an array of petitions and append those matching a search term to an array of filtered petitions.

func filterCells() {
        if filterText != nil {
            filteredPetitions = []
            for petition in petitions {
                if petition.body.contains(filterText!) {
                    filteredPetitions.append(petition)
                    print(filteredPetitions.count)
                }
            }
        } else {
            for petition in petitions {
                filteredPetitions.append(petition)
                print(filteredPetitions.count)
            }
        }
    }

The function should:

  1. Check to see if filterText exists.
  2. If not, transfer everything in the petitions array to the filteredPetitions array. Count off each one in the terminal.
  3. If filterText exists, empty the filteredPetitions array.
  4. Step through each petition, look for the search term, and add those that contain it to filteredPetitions. Count off each one in the terminal.

The function runs at first load and is meant to run after the user submits their search term. So all is well after the app is opened, but it crashes with an "Index out of range" error when the user taps submit. This is telling me that after the array is emptied Step 4 is not happening.

What am I doing wrong here?

2      

Chris asks for advice:

What am I doing wrong here? ... snip... [app] crashes with an "Index out of range" error

One of the first things that I see is you're not using powerful array features. I've followed the 100 Days of SwiftUI, so am not sure the order of some of your lessons. But is seems you missed a major lesson on filtering arrays. Just a guess, but I think the goal of Project 7 is to apply what you learned about powerful built-in array functions.

Instead, you are writing your own. This is also a good lesson because by writing your own, you've introduced bugs. This is wasteful and annoying. Instead, teach yourself to rely on built-in functions, they are convenient, fast, and bug-free!

See-> Filtering Arrays

Also, when I see code like this:

else {
// Why are you building your own "array transfer" code? 
    for petition in petitions {
        filteredPetitions.append(petition)
        print(filteredPetitions.count)
    }
}

I think, "Chris is just transferring the contents of one array to another." If so, why not just make an assignment?

// Don't write your own! Just make a copy.
else {
    filteredPetitions = petitions // just return ALL the petitions, no filters!
}

3      

Thanks, Obelix. That definitely put me on the right track.

Here's the updated function:

func filterCells() {

        if filterText == nil {
            filteredPetitions = petitions
        } else {
            filteredPetitions = petitions.filter {
                $0.body.range(of: filterText!, options: .caseInsensitive) != nil
            }
            print(filteredPetitions.count)
            print(filteredPetitions)
            if filteredPetitions.count == 0 {
                let ac = UIAlertController(title: "No results found", message: "Looks like the American people don't care about that issue.", preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "Fools!", style: .default))
                present(ac, animated: true)
                filteredPetitions = petitions
            }
        }
    }

However, that turned out to be only part of the problem. Turns out I forgot to switch my numberOfRowsInSection from petitions.count to filteredPetitions.count:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredPetitions.count
    }

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.