I have this var json : [[String : Any]] = [[:]]
which contains the JSON response as follows:
{
"id": "1",
"name": "Apple",
"category_name": "Fruits"
},
{
"id": "2",
"name": "Black shirt",
"category_name": "Fashion"
},
{
"id": "3",
"name": "iPad",
"category_name": "Gadgets"
}
And I wrote an enum:
enum : Int {
case fruits = 0, fashion, gadgets
}
var data = [Categories: [[String: Any]]]()
Then I have this method to sort the categories:
func sortData() {
data[.fruits] = self.json.filter({ $0["category_name"] == "Fruits" })
data[.fashion] = self.json.filter({ $0["category_name"] == "Fashion" })
data[.gadgets] = self.json.filter({ $0["category_name"] == "Gadgets" })
}
After that I get an error like this
Binary operator '
==
' cannot be applied to operands of type 'Any?
' and 'String
'
Please tell me how do I solve that one?
You should safely cast the value on the left to String
, like this:
data[.fruits] = self.json.filter({ ($0["category_name"] as? String) == "Fruits" })