Filtering json

I am trying to filter a json with a UICollectionView. It sorts but does not filter. What is going wrong. The collectionView works, the segue works, the records are sorted, but not filtered on the subjectitem. I am working with the storyboard and connected the segue from the cell to the fragment.


class SubjectViewController: UIViewController {
    @IBOutlet var collectionView: UICollectionView!
    
    var subjects: [SubjectItem] = [
        SubjectItem(imageName: "grace", name:"Grace"),
        SubjectItem(imageName: "family", name: "Family"),
        SubjectItem(imageName: "life", name: "Life"),
        SubjectItem(imageName: "love", name: "Love"),
        SubjectItem(imageName: "nature", name: "Nature"),
        SubjectItem(imageName: "telios", name: "Telios"),
        SubjectItem(imageName: "words", name: "Words"),
        SubjectItem(imageName: "work", name: "Work"),
        // Add other subjects
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self
    }
}

struct SubjectItem {
    let imageName: String
    let name: String
}

extension SubjectViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return subjects.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubjectCell", for: indexPath) as! SubjectCell
        let subject = subjects[indexPath.item]
        cell.configure(with: subject)
        return cell
    }
}

extension SubjectViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let selectedSubject = subjects[indexPath.item]
        navigateToPoemFragment2(with: selectedSubject)
    }
    
    func navigateToPoemFragment2(with subject: SubjectItem) {
        print("Selected Subject: \(subject.name)")
        if let poemFragment2 = storyboard?.instantiateViewController(withIdentifier: "PoemSortedList") as? PoemFragment2 {
            poemFragment2.selectedSubject = subject // Set the selectedSubject property
            navigationController?.pushViewController(poemFragment2, animated: true)
        }
    }


}

class SubjectCell: UICollectionViewCell {
    @IBOutlet var imageView: UIImageView!
    @IBOutlet var nameLabel: UILabel!

    func configure(with subject: SubjectItem) {
        imageView.image = UIImage(named: subject.imageName)
        nameLabel.text = subject.name
    }
}


import UIKit

class PoemFragment2: UITableViewController {
    
    @IBOutlet var poemTableView2: UITableView!
    
    var allPoems: [Poem] = [] // Store all poems here
    var filteredPoems: [Poem] = [] // Store filtered poems here
    var selectedSubject: SubjectItem? // This should be set when navigating from SubjectViewController
    
    override func viewDidLoad() {
        super.viewDidLoad()
        parseJSON()
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredPoems.count // Use filtered poems for table view data source
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let poem = filteredPoems[indexPath.row]
        let cell = poemTableView2.dequeueReusableCell(withIdentifier: "PoemCell2", for: indexPath) as! PoemTableViewCell2
        cell.poemName2.text = poem.poemName
        cell.subject2.text = poem.subject
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "poemDetail2", sender: self)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? PoemDetailFragment2,
           let indexPath = tableView.indexPathForSelectedRow {
            destination.poem = filteredPoems[indexPath.row] // Pass the selected poem
        }
    }
    
    private func parseJSON() {
        guard let path = Bundle.main.path(forResource: "poem", ofType: "json") else {
            return
        }
        
        let url = URL(fileURLWithPath: path)
        
        do {
            let jsonData = try Data(contentsOf: url)
            allPoems = try JSONDecoder().decode(PoemData.self, from: jsonData).poem
            print("All Poems: \(allPoems)")
            filterAndSortPoems() // After parsing, apply filter and sort
        } catch {
            print("Error: \(error)")
        }
    }
    
    func filterAndSortPoems() {
        if let selectedSubject = selectedSubject {
            // Print the selected subject for debugging
            print("Selected Subject: \(selectedSubject.name)")
            
            // Filter poems by selected subject
            filteredPoems = allPoems.filter { poem in
                return poem.subject.localizedCaseInsensitiveCompare(selectedSubject.name) == .orderedSame
            }
            
            // Sort the filtered poems by subject
            filteredPoems.sort { $0.subject.localizedCaseInsensitiveCompare($1.subject) == .orderedAscending }
        } else {
            // If no subject is selected, show all poems
            filteredPoems = allPoems
            
            // Sort all poems by subject
            filteredPoems.sort { $0.subject.localizedCaseInsensitiveCompare($1.subject) == .orderedAscending }
        }
        
        // Print the filtered result for debugging
        print("Filtered Result: \(filteredPoems)")
        tableView.reloadData() // Reload the table view with filtered data
    }
}

Can you narrow down where it goes wrong? Does it take the expected branch in filterAndSortPoems()? If so, is the filter call not working correct? Or is something going wrong earlier?

Did you try without localizing (caseInsensitiveCompare) ?

Could you add another print:

    func filterAndSortPoems() {
        if let selectedSubject = selectedSubject {
            // Print the selected subject for debugging
            print("Selected Subject: \(selectedSubject.name)")
            // Filter poems by selected subject
            filteredPoems = allPoems.filter { poem in
                print(poem.subject)
                return poem.subject.localizedCaseInsensitiveCompare(selectedSubject.name) == .orderedSame
            }
Filtering json
 
 
Q