0

Json response like this

{
"categories": [
    {
        "id": 48,
   
        "products": [
            {
                "name": ".Tea",
                "food_type": "veg",

Code: with this code i am able to show all first category products in tableview.. here if i click vegSwitch i need to show only "food_type": "veg" related products in tableview

 class FoodsMenuVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var vegSwitch: UISwitch!
var foodType: String = ""
var filterArray: : Category?
var categoryArray: Category?
private var catData: Categories? {
    didSet{
     
        categoryArray = catData?.categories?[0]

        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
}

@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()

    foodMenuServicecall()
}

@IBAction func vegSwitch(_ sender: UISwitch) {
    
    if sender.isOn{
        filterArray = categoryArray?.products?.filter { $0.foodType?.rawValue == "veg" }
    }
    else{
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return categoryArray?.products?.count ?? 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "FoodIteamsCell", for: indexPath) as! FoodIteamsCell
    cell.selectionStyle = .none
    
    if let eachCat = categoryArray{
        
        cell.nameLbl.text = eachCat.products?[indexPath.row].name?.capitalized
        
        for oneImg in eachCat.products?[indexPath.row].images ?? []{
            cell.iteamImg.sd_setImage(with: URL(string: oneImg.url ?? ""), placeholderImage: UIImage(named: "placeholder.png"))
        }
    }
    return cell
}
}

if i try like this in vegSwitch button filterArray = categoryArray?.products?.filter { $0.foodType?.rawValue == "veg" }

error:

Cannot assign value of type '[Product]?' to type 'Category?'

please guide me to filter JSON

1
  • You are filtering category?.products which returns an array of products which is of type [Product]?. This cannot be assigned to filterArray since its type is Category?. Commented Mar 3, 2022 at 15:57

1 Answer 1

0

Let's analyze:

You have:

var filterArray: : Category?
var categoryArray: Category?

Then, you do:

filterArray = categoryArray?.products?.filter { $0.foodType?.rawValue == "veg" }

Which is equivalent, once "broken into multiple statements":

let products: [Product]? = categoryArray?.products
let filtered: [Product] = products?.filter { $0.foodType?.rawValue == "veg" }
filterArray = filtered //Here it fails, because `filterArray` is a Category and filtered a `[Product]`

So the solution would be to have extra method to Category:

extension Category {
    static func make(fromCategory category: Category, withProducts products: [Product]) -> Category {
        return Category(id: category.id, products: products)
    }
}

I use only id & products properties, since I don't know if there are more, but add them if needed.

Then, now, you can construct a Category that you can build from existing Category & filtered products.

In use:

let filterArray = categoryArray.compactMap { aCategory -> Category? in
    let filteredProducts = aCategory.products.filter { $0.foodType == "veg" }
    if filteredProducts.isEmpty {
        return nil // or Category.make(fromCategory: aCategory, withProducts: []), or just ignore the if test if it's fine to have a section category without products
    }
    return Category.make(fromCategory: aCategory, withProducts: filteredProducts)
}

But, according to your code, you don't seem to use Category, so get rid of it, and just use an array of products directly.

Sign up to request clarification or add additional context in comments.

8 Comments

cant we do filter without using extension Category... i am learnig swift codes.. for me above code is hard to understand... could you make it easy please... with that extension i donno how to show tableview
Put make(fromCategory:withProduct) inside struct Category, there is not need for a category in reality.
in my code how to do filter with food_type for products in categories.. and show in tableview
I've shown how to replace filterArray = categoryArray?.products?.filter { $0.foodType?.rawValue == "veg" } with let filterArray = categoryArray.compactMap , it doesn't work?
i couldn't understand where to replace
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.