可能将这个Alamofire的结果转化为一系列的字典

可能将这个Alamofire的结果转化为一系列的字典

本文介绍了可能将这个Alamofire的结果转化为一系列的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是一个iOS开发者,必须对Swift / AlamoFire项目(不是我的)进行一些修改,并且有点迷失。



我有以下JSON:

  {metro_locations: 
[
{
name:Ruby Red
},
{
name:Blue Ocean
}
]
}

class(我知道这里有问题)

  class Location {
var name =
init(obj:tmp){
self.name = tmp [name]
}
}

并且需要进行AlamoFire调用

  Alamofire.request(.GET,https://www.domain.com/arc / v1 / api / metro_areas / 1,参数:nil)
.responseJSON {response in

如果让dataFromNetworking = response.result.value {
let metroLocations = dataFromNetworking [ metro_locations]
var位置:[位置] = []
为tmp在metroLocations为! [Dictionary] {//< - not working,Generic Paramter'Key'无法推断
let location = Location.init(obj:tmp)
locations.append(location)

}
}

我已经包含错误msg,not工作,但感觉在其他部分也有问题(比如在初始化中期待一个字典)。 Key不能被推断是什么意思,还有其他需要修改的内容?



编辑#1


$ b $我已经更新了我的位置,以反映您的建议:

  init?(dictionary:[String:AnyObject] ){
guard let id = dictionary [id] else {return nil}
guard let name = dictionary [name] else {return nil}
guard let latitude = 纬度] else {return nil}
guard let longitude = dictionary [longitude] else {return nil}
self.name = name as! String
self.id = id as! int
self.latitude =纬度为!双倍
self.longitude =经度为! Double
}

但是我收到错误:

 无法将类型NSNull(0x10f387600)的值转换为NSNumber(0x10f77f2a0)。 

像这样:





我认为 guard 语句会阻止这种情况。我失踪了什么

解决方案

您可以将 metroLocations 作为一个字典数组,即:

 数组<字典< String,String>> 

或者更简洁:

  [[String:String]] 

因此:

 如果让dataFromNetworking = response.result.value {
guard let metroLocations = dataFromNetworking [metro_locations] as? [[String:String]] else {
print(这不是字符串数组,其中所有的字符串都是字符串)
return
}

var locations = [位置]()
在metroLocations中的字典{
如果let location =位置(字典:字典){
locations.append(location)
}

}

其中

  class Location {
let name:String

init?(dictionary:[String:String]){
guard let name = dictionary [name] else {return nil}
self.name = name
}
}

显然,我使用 [[String:String]] 来表示一个字典的数组,其中的值都是字符串,如你的例子。如果值包含字符串(数字,布尔等)之外的对象,则可以使用 [[String:AnyObject]]






在您的修订版本中,您向我们展示了更完整的位置实现。您应该避免 as!强制投放,而是 guard 语句:

  class Location {
let id:Int
let name:String
允许纬度:Double
让经度:Double

init?(dictionary:[String:AnyObject]){
guard let id = dictionary [id]如? Int,
let name = dictionary [name] as? String,
let latitude = dictionary [latitude] as? Double,
让longitude = dictionary [longitude] as? Double else {
return nil
}
self.name = name
self.id = id
self.latitude = latitude
self.longitude = longitude
}
}


I am not an iOS dev and have to make a few changes to a Swift / AlamoFire project (not mine) and am a bit lost.

I have the following JSON:

{"metro_locations":
 [
   {
     "name":"Ruby Red"
   },
   {
      "name":"Blue Ocean"
    }
  ]
}

class (I know that there are issues here):

class Location{
  var name=""
  init(obj:tmp){
    self.name=tmp["name"]
  }
}

and need to make an AlamoFire call

Alamofire.request(.GET, "https://www.domain.com/arc/v1/api/metro_areas/1", parameters: nil)
  .responseJSON { response in

    if let dataFromNetworking = response.result.value {
      let metroLocations = dataFromNetworking["metro_locations"]
      var locations: [Location]=[]
      for tmp in metroLocations as! [Dictionary] { // <- not working, Generic Paramter 'Key' could not be inferred
        let location=Location.init(obj: tmp)
        locations.append(location)
      }
    }
}

I have included the error msg, the "not working" but feel that there are issues in other parts too (like expecting a dictionary in the initialization). What does the 'Key' could not be inferred mean and are there other changes I need to make?

edit #1

I have updated my Location to this to reflect your suggestion:

  init?(dictionary: [String: AnyObject]) {
    guard let id = dictionary["id"] else { return nil }
    guard let name = dictionary["name"] else { return nil }
    guard let latitude = dictionary["latitude"] else { return nil }
    guard let longitude = dictionary["longitude"] else { return nil }
    self.name = name as! String
    self.id = id as! Int
    self.latitude = latitude as! Double
    self.longitude = longitude as! Double
  }

but I get the error:

Could not cast value of type 'NSNull' (0x10f387600) to 'NSNumber' (0x10f77f2a0).

like this:

I would think that the guard statement would prevent this. What am I missing?

解决方案

You can cast metroLocations as an array of dictionaries, namely:

Array<Dictionary<String, String>>

Or, more concisely:

[[String: String]]

Thus:

if let dataFromNetworking = response.result.value {
    guard let metroLocations = dataFromNetworking["metro_locations"] as? [[String: String]] else {
        print("this was not an array of dictionaries where the values were all strings")
        return
    }

    var locations = [Location]()
    for dictionary in metroLocations {
        if let location = Location(dictionary: dictionary) {
            locations.append(location)
        }
    }
}

Where

class Location {
    let name: String

    init?(dictionary: [String: String]) {
        guard let name = dictionary["name"] else { return nil }
        self.name = name
    }
}

Clearly, I used [[String: String]] to represent an array of dictionaries where the values were all strings, as in your example. If the values included objects other than strings (numbers, booleans, etc.), then you might use [[String: AnyObject]].


In your revision, you show us a more complete Location implementation. You should avoid as! forced casting, and instead us as? in the guard statements:

class Location {
    let id: Int
    let name: String
    let latitude: Double
    let longitude: Double

    init?(dictionary: [String: AnyObject]) {
        guard let id = dictionary["id"] as? Int,
            let name = dictionary["name"] as? String,
            let latitude = dictionary["latitude"] as? Double,
            let longitude = dictionary["longitude"] as? Double else {
                return nil
        }
        self.name = name
        self.id = id
        self.latitude = latitude
        self.longitude = longitude
    }
}

这篇关于可能将这个Alamofire的结果转化为一系列的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 23:19