【问题标题】:How to access array of dictionaries in swift如何快速访问字典数组
【发布时间】:2016-10-18 19:44:04
【问题描述】:

我有array,其中包含dictionaries。这就是我尝试访问数组的方式。

这是怎么回事?

let aWeather: Dictionary = arrWeatherDeatils[indexPath.row]! as!Dictionary

当我使用此代码时,xcode 显示此错误:

Command failed due to signal: Segmentation fault: 11

【问题讨论】:

  • 提供更多代码?
  • 你的数组 arrWeatherDetails 是 WS 响应吗??
  • 不,这不是直接的 WS 响应。我从 plist 中读取到 arrWeatherDetails
  • stackoverflow.com/questions/36292679/… 这可能会有所帮助

标签: ios arrays swift dictionary


【解决方案1】:
let aWeather: Dictionary<AnyObject,AnyObject> = arrWeatherDeatils[indexPath.row]! as! Dictionary<AnyObject,AnyObject>

【讨论】:

    【解决方案2】:

    像下面这样写字典,

     let aWeather : NSDictionary = arrWeatherDeatils.objectAtIndex(indexPath.row) as! NSDictionary
    

    解决segmentation fault:11错误,

    试试这个,进入 Build Settings -> Swift Compiler - Code generation,将 Optimization Level 设置为 None。

    希望这会对你有所帮助。

    【讨论】:

    • 我为什么要使用 NSDictionary?如果使用 NSDictionary,我可以像这个单元格一样访问字典对象吗!.lblAvgHome.text = (aWeather["home"]!["avg"]!)
    • 是的,cell!.lblAvgHome.text = aWeather.valueForKey("home")?.valueForKey("avg") as!字符串
    【解决方案3】:
    var arrWeatherDeatils = [
        "Sunny": 76.0,
        "Chilly": 22.1,
        "Warm": 37.0
    ]
    
    var typeList: [String] {
        get {
            return Array(arrWeatherDeatils.keys)
        }
    }
    

    然后在你的cellForRowAtIndexPath

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //note I did not check for nil values. Something has to be really         let row = indexPath.row //get the array index from the index path
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        let myRowKey = typeList[row] //the dictionary key
        cell.textLabel!.text = myRowKey
        let myRowData = arrWeatherDeatils[myRowKey] //the dictionary value
        cell.detailTextLabel!.text = String(format: "%6.3f",myRowData!)
        return cell
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2022-01-22
      • 2015-10-31
      • 2019-10-16
      • 2020-11-12
      • 2016-01-20
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多