从Swift数组中获取特定值

时间:2018-02-12 15:40:14

标签: arrays json swift

因此,我使用SwiftyJSON从API下载数据。我正在转换它,并循环以获得所有结果。我试图将每个结果的特定部分打印出来,但我似乎无法使其正常工作。

我在下面使用的代码接受json,并循环遍历它并打印出下面的内容。从印刷的内容来看,我只是想得到“主题”。

ListView

然后给出如下值:

do {
            let jsonObj = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
            let json = JSON(jsonObj)


            let pms: NSArray = json["result"]["pms"].arrayValue as NSArray


            let arrayLength = pms.count

            for var i in (0..<arrayLength) {
                let pm = pms[i]

                i+=1

            }

        } catch let error as NSError {
            print(error)
        }

如果我尝试类似

的话
{
  "subject" : "Example",
  "status" : 1,
  "recipient" : 012345,
  "recipientusername" : "Example",
  "dateline" : "2018-01-01",
  "sender" : 012345,
  "pmid" : 012345,
  "senderusername" : "DoctorSheep"
}
{
  "subject" : "Example 2",
  "status" : 1,
  "recipient" : 678910,
  "recipientusername" : "Example 2",
  "dateline" : "2018-01-01",
  "sender" : 678910,
  "pmid" : 678910,
  "senderusername" : "Example 2"
}

我收到错误“类型'任何'没有下标成员”。

1 个答案:

答案 0 :(得分:0)

let pms = json["result"]["pms"].arrayValue as Array


let arrayLength = pms.count

for var i in (0..<arrayLength) {
    let pm = pms[i]
    let subject = pm["subject"]
    print(subject)
    i+=1
}