Swift:通过字典数组循环

时间:2015-02-18 18:55:09

标签: arrays json swift dictionary struct

我正在努力遍历从Web服务调用返回的字典值数组。

我已经实现了以下代码,我似乎遇到了运行崩溃。

我还希望将结果存储到自定义Struct中。真的很难实现这一点,到目前为止这里的答案还没有奏效。如果有人能够提供帮助,将不胜感激。

    let nudgesURLString = "http://www.whatthefoot.co.uk/NUDGE/nudges.php"
    let nudgesURL = NSURL(string: nudgesURLString)

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithURL(nudgesURL!, completionHandler: {data, response, error -> Void in

        if error != nil {
            println(error)
        } else {

           let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

            let nudges: NSDictionary = nudgesJSONResult["nudges"] as NSDictionary

            if let list = nudgesJSONResult["nudges"] as? [[String:String]] {
                for nudgeDict in list {
                    let location = nudgeDict["location"]
                    println(location)
                }
            }

        }

    })

    task.resume()

}

2 个答案:

答案 0 :(得分:2)

通知

这个答案是使用Swift 1.2编写的,因此,根据您当前的Swift系统,可能需要进行一些轻微的风格和语法更改才能解决问题。

答案 - Swift 1.2

此行正在崩溃您的代码:

let nudges: NSDictionary = nudgesJSONResult["nudges"] as NSDictionary

你强迫Swift无法处理的演员阵容。你永远不会把它变成你的for循环。

尝试将代码更改为更像这样:

let nudgesURLString = "http://www.whatthefoot.co.uk/NUDGE/nudges.php"
let nudgesURL = NSURL(string: nudgesURLString)

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(nudgesURL!, completionHandler: {data, response, error -> Void in
    if error != nil {
        println(error)
    } else {
        let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as [String : AnyObject]
        if let nudges = nudgesJSONResult["nudges"] as? [[String : String]] {
            for nudge in nudges {
                let location = nudge["location"]
                println("Got location: \(location)")
                println("Got full nudge: \(nudge)")
            }
        }
    }

})

task.resume()

答案 1 :(得分:0)

谢谢,

我创建了以下用于存储数据的Struct,并且还允许我在视图控制器中为特定索引创建词典。

struct NudgesLibrary {

var location: NSArray?
var message: NSArray?
var priority: NSArray?
var date: NSArray?
var nudges: NSArray?

init(nudgesObject: AnyObject) {

    nudges = (nudgesObject["nudges"] as NSArray)

    if let nudges = nudgesObject["nudges"] as? NSArray {
        location =  (nudges.valueForKey("location") as NSArray)
        message = (nudges.valueForKey("message") as NSArray)
        priority = (nudges.valueForKey("priority") as NSArray)
        date = (nudges.valueForKey("date") as NSArray)

    }
  }
}