在swift中循环内部循环

时间:2015-11-05 00:34:59

标签: ios arrays swift

我有一个像这样的数组的JSON文件

"vars": [
                  {
                     "key": "f1",
                     "link": "@cooldownchampion",
                     "coeff": [
                        24,
                        23,
                        22,
                        21,
                        20
                     ]
                  },
                  {
                     "key": "f4",
                     "link": "@text",
                     "coeff": [
                        150,
                        175,
                        200,
                        225,
                        250,
                        275,
                        300,
                        325,
                        350,
                        375,
                        400,
                        425,
                        450,
                        475,
                        500,
                        525,
                        550,
                        575
                     ]
                  }
               ]

我想循环内循环来获取coeff的所有条目

这是我的循环

for (key,subJson):(String, JSON) in newjson["vars"]{
   for (key,subJson):(String, JSON) in newjson["vars"][key]["coeff"]{
      print (subJson) // this should print 24/23/22/21 but it doesn't
}

}

如您所知,我使用SWIFTYJSON库来处理JSON FILE

3 个答案:

答案 0 :(得分:0)

问题是您的第一个keyString,并且要按索引访问元素需要Int

您可以通过投射来解决问题:

for (key,subJson):(String, JSON) in newjson["vars"] {
    for (key,subJson):(String, JSON) in newjson["vars"][Int(key)!]["coeff"]{
        print (subJson) // this should print 24/23/22/21 but it doesn't
    }
}

但更好的方法是使用现有的JSON对象(subJson),如下所示:

for (key,subJson):(String, JSON) in newjson["vars"] {
    for (key,subJson):(String, JSON) in subJson["coeff"]{
        print (subJson) // this should print 24/23/22/21 but it doesn't
    }
}

答案 1 :(得分:0)

for (key,subJson):(String, JSON) in newjson["vars"]{
   for (key,subJson):(String, JSON) in newjson["vars"][indexInTheArray]["coeff"]{
      print (subJson) // this should print 24/23/22/21 but it doesn't
}

}

使用key:String索引数组,indexInTheArray应该是一个整数

答案 2 :(得分:-1)

我不知道如何使用swift进行编码

如果使用object-c

$data = DB::table('workorders')
   ->select('noworkorder')
   ->whereYear('date', '=', 2015)
   ->orderby('noworkorder', 'desc')
   ->get();