【发布时间】:2019-10-18 10:56:50
【问题描述】:
我正在尝试在我的 JSON 中查找特定值。
这是我的 json
[
{
"airportName" : "Simon Mwansa Kapwepwe Intl",
"longitude" : 28.664999999999999,
"geometry" : {
"type" : "Point",
"coordinates" : [
28.664999999999999,
-12.994999999999999
]
},
"countryCode" : "ZMB",
"countryName" : "Zambia",
"latitude" : -12.994999999999999,
"cityName" : "Ndola",
"airportCode" : "FLSK"
},
{
"airportName" : "Mafikeng",
"longitude" : 25.544469444444445,
"geometry" : {
"type" : "Point",
"coordinates" : [
25.544469444444445,
-25.807447222222223
]
},
"countryCode" : "ZAF",
"countryName" : "South African Rep",
"latitude" : -25.807447222222223,
"cityName" : "Mafikeng",
"airportCode" : "FAMM"
}]
现在,如果我编写此代码,它就可以工作了!
for item in 0...json.count {
i = i+1
if json[i]["airportName"] == "Simon Mwansa Kapwepwe Intl" {
print ("I found it")
}
如果我尝试将参数传递给一个不起作用的函数进行搜索,请迅速给我一个错误说:二进制运算符'=='不能应用于'JSON'和'String'类型的操作数
func cerca (nomeApt: String){
var i = 0
for item in 0...json.count {
i = i+1
if json[i]["airportName"] == nomeApt { // error I don't know
print ("I found it")
}
}
}
老实说,我不知道为什么?知道如何解决这个问题吗?非常感谢
【问题讨论】:
-
如果您使用
CodableIMO,这会容易得多。题外话,但你的for循环很糟糕,它错过了数组中的第一个元素,最后会生成索引越界错误。