首页 > 解决方案 > 对成员 'decode(_:forKey:)' swift4 的模糊引用

问题描述

我正在解析一个需要从服务器上的字典(这是一种遗留数据格式)转换为简单的客户端字符串数组的响应。因此,我想将名为“数据”的键解码为字典,这样我就可以遍历键并在客户端创建一个字符串数组。

init(from decoder: Decoder) throws  {
  let values = try decoder.container(keyedBy: CodingKeys.self)
  do {
    let some_data_dictionary = try values.decode([String:Any].self, forKey: CodingKeys.data)

    for (kind, values) in some_data_dictionary {
      self.data_array.append(kind)  
    }
  } catch {
    print("we could not get 'data' as [String:Any] in legacy data \(error.localizedDescription)")
  }
}

我得到的错误是:Ambiguous reference to member 'decode(_:forKey:)'

标签: swiftswift4codable

解决方案


看起来 Swift 'Codable' 不能支持 Any 或使用 [String:Any],所以在这里使用这篇文章Swift 4 decodable nested json with random key attributes

我能够为我不会使用的名为 LegacyData 的类创建一个结构,然后将键解压缩到字符串数组中

    do
    {
      let legacy_data = try values.decode([String:LegacyData].self, forKey: CodingKeys.data)

      self.array = Array(legacy_data.keys)
    }
    catch
    {
      print("no legacy_data \(error) \n")
    }

推荐阅读