【问题标题】:Why is my commonName repeating the same in my loop?为什么我的 commonName 在我的循环中重复相同?
【发布时间】:2016-02-23 16:00:20
【问题描述】:

from this link我得到相同的 commonName 但它应该不同?!

let jsonData = NSData(contentsOfURL: url!)
let readableJSON = JSON(data: jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil)
let object = try! NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>
let json = JSON(object)

for (_,object):(String, JSON) in readableJSON { 
    let commonName = json["toLocationDisambiguation"]["disambiguationOptions"][0]["place"]["commonNam‌​e"].stringValue 
    commonNameArray.append(commonName)
}

【问题讨论】:

  • 但我希望每一个都能得到不同的价值?!
  • 是因为我在 For 循环中设置了我的变量吗?

标签: json swift loops for-loop


【解决方案1】:

因为 [0],你需要做类似的事情

var i = 0
for (_,object):(String, JSON) in readableJSON { 
    let commonName = json["toLocationDisambiguation"]["disambiguationOptions"][i]["place"]["commonNam‌​e"].stringValue 
    commonNameArray.append(commonName)
i = i+1
}

【讨论】:

    【解决方案2】:

    在您的for 循环中,您总是只获取disambiguationOptions 数组的0th 元素。相反,您需要使用索引来获取数组的每个元素。

    【讨论】:

      【解决方案3】:

      您的循环毫无意义,它遍历顶部字典的键/值对,但不使用它们。相反,您也总是使用从顶层开始的相同引用检索相同的对象。

      包含commonName 键的基本数组对象是disambiguationOptions

      此代码遍历数组的所有项。

      var commonNameArray = [String]()
      let jsonData = NSData(contentsOfURL: url!)
      let readableJSON = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String:AnyObject]
      let object = JSON(readableJSON)
      let disambiguationOptions = object["toLocationDisambiguation"]["disambiguationOptions"]
      for option in disambiguationOptions.arrayValue {
        let commonName = option["place"]["commonName"].stringValue
        commonNameArray.append(commonName)
      }
      

      【讨论】:

      • 太棒了!回家后我会尝试一下,谢谢..感谢其他帮助过我的人!
      • 我试过了,它几乎成功了,当我 NSLog 时它似乎可以正确输出,但我收到一个致命错误:数组索引超出范围stackoverflow.com/questions/35587724/…
      • 我在 Playground 中成功测试了该代码
      • 是的,正如我所说,它输出正确,但会破坏应用程序和错误?!
      • out of range 错误与该代码无关。
      猜你喜欢
      • 2012-10-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2018-06-18
      • 2022-12-10
      • 1970-01-01
      相关资源
      最近更新 更多