【问题标题】:Adding json items to dictionary in Swift在 Swift 中将 json 项添加到字典中
【发布时间】:2015-03-18 18:35:46
【问题描述】:

我刚开始使用 Swift,我正在尝试遍历 json 响应并将其添加到字典中。但似乎没有添加任何内容,不确定问题可能是范围?我正在使用 SwiftyJSON。在我的代码中,我可以在 for 循环中打印新闻标题,例如 json[0]["title"] 等。但是当我打印字典的值时,什么都没有输出。

// news dictionary
var newsDictionary = [String] ()

override func viewDidLoad() {
    super.viewDidLoad()

    // get news feed url
    let url = NSURL(string: baseUrl + "news")

    // create session
    let session = NSURLSession.sharedSession()

    // create data task
    let task = session.dataTaskWithURL(url!, completionHandler: { (data: NSData!, response:NSURLResponse!,
        error: NSError!) -> Void in

        // convert data object to json
        let json = JSON(data: data)

        for var i = 0; i < json.count; ++i {
            // get news title from json object
            var title = json[i]["title"].string
            // add to dictionary
            self.newsDictionary.append(title!)
        }

    })

    for news in newsDictionary{
        println(news)
    }

    // execute call
    task.resume()





    // Do any additional setup after loading the view.
}

【问题讨论】:

标签: json swift


【解决方案1】:

这是因为你有一个竞争条件。在session.dataTaskWithURL 中下载和处理任何数据之前,您的for news in newsDictionary 循环很可能正在执行。

for 循环放入completionHandler 中,您应该会看到数据。

【讨论】:

  • 在代码方面看起来像什么?为我的新手状态道歉!
  • 您已经编写了一个完成处理程序,只需移动“for news in newsDictionary”循环,使其紧跟另一个 for 循环。基本上,它只需要在 }) 之前
  • @WillM。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2023-03-20
  • 2017-07-27
  • 1970-01-01
相关资源
最近更新 更多