二进制运算符'=='不能应用于'Any?'类型的操作数和'String'Swift iOS [英] Binary operator '==' cannot be applied to operands of type 'Any?' and 'String' Swift iOS
本文介绍了二进制运算符'=='不能应用于'Any?'类型的操作数和'String'Swift iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个 var json:[[String:Any]] = [[:]]
,其中包含JSON响应,如下所示:
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"
}
我写了一个枚举:
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" })
}
之后我收到这样的错误
二元运算符'
==
'无法应用于'类型的操作数任何?
'和
'字符串
'
Binary operator '
==
' cannot be applied to operands of type 'Any?
' and 'String
'
请告诉我如何解决这个问题?
Please tell me how do I solve that one?
推荐答案
您应该安全地将左侧的值转换为 String
,如下所示:
You should safely cast the value on the left to String
, like this:
data[.fruits] = self.json.filter({ ($0["category_name"] as? String) == "Fruits" })
这篇关于二进制运算符'=='不能应用于'Any?'类型的操作数和'String'Swift iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文