【问题标题】:Casting an AnyObject to a Dictionary nested in an Array将 AnyObject 转换为嵌套在数组中的字典
【发布时间】:2016-10-08 06:03:02
【问题描述】:

我希望将 AnyObject 变量转换为嵌套在数组中的字典。例如,我在函数中声明变量:

var items: [[String:String]] = [
     [
         "pid": "1",
         "content": "123",
         "vote": "1",
         "city": "New York",
         "country": "United States"
     ]
 ]

然后我从 HTTP 请求中获取 JSON 对象并将其转换为 AnyObject。然后,我尝试将 HTTP 请求获取的数据作为 AnyObject 附加到原始变量上。

此过程在将 AnyObject 转换为所需的 [[String: String]] 形式时失败。

func updateTable(data: AnyObject?) {
    let data_array = (data as! NSArray) as! Array<Dictionary<String, String>>

    self.items += data_array
}

此功能包括变量的转换和数组的添加。

我怎样才能正确地转换这个变量?

编辑 我忘了提到我在通过函数之前将我的序列化 JSON 输出转换为 [AnyObject]

【问题讨论】:

  • 试试这个 => 让 data_array = data as! NSDictionary
  • 与原变量不兼容的是[[String: String]]
  • 试试这个 => data as Dictionary
  • 也不起作用,它说“无法将 [[String, String]] 类型的值转换为预期的参数类型 'input_'

标签: ios swift dictionary casting


【解决方案1】:

我认为您需要转换数组的各个元素。

func updateTable(data: [AnyObject]) {
for item in data {
    if let item = item as? [String: String] {
        items.append(item)
    }
}

或者如果你想更简洁......

func updateTable(data: [AnyObject]) {
    items += data.flatMap({$0 as? [String: String]})
}

【讨论】:

    猜你喜欢
    • 2013-12-07
    • 1970-01-01
    • 2018-02-16
    • 2015-12-22
    • 2022-12-05
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多