问题
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?
回答1:
You should safely cast the value on the left to String
, like this:
data[.fruits] = self.json.filter({ ($0["category_name"] as? String) == "Fruits" })
回答2:
The problem is that you're trying to compare values of differing types, namely Any?
and String
. To quickly solve the problem you might want to try and convince Swift that your Any?
is actually a string value. Try replacing $0["category_name"]
with ($0["category_name"] as? String)
, which will turn it into String?
. Swift will then be able to compare the optional string with your given category string.
回答3:
Swift 5
Change following codes from
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" })
}
to
func sortData() {
data[.fruits] = self.json.filter({ $0["category_name"] as? String == "Fruits" })
data[.fashion] = self.json.filter({ $0["category_name"] as? String == "Fashion" })
data[.gadgets] = self.json.filter({ $0["category_name"] as? String == "Gadgets" })
}
This will fix the error.
来源:https://stackoverflow.com/questions/47139150/binary-operator-cannot-be-applied-to-operands-of-type-any-and-string-s