WWDC22 SALE: 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?

   

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!
}

1      

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
    }

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

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.