无法为索引类型为“任何”的下标“ [[AnyHashable:任何]””下标。

时间:2019-03-08 16:09:28

标签: arrays swift dictionary nsdictionary

我正在尝试将目标c函数转换为swift。

   +(NSString *)extractNameWithDictionary:(NSDictionary *)dictionary
{

   NSDictionary *assets = dictionary[@"assets"];
   NSDictionary *item = dictionary[@"item"];
   NSArray *facilityAssets = item[@"assets"];
   NSDictionary *facilities = facilityAssets[0];
   NSDictionary *asset = assets[facilities[@"content"]];

   return asset[scs_name] ? : @"";
}

收件人

func extractNameWithDictionary(dictionary: [AnyHashable : Any]) -> String {
    guard let assets = dictionary["assets"] as? [AnyHashable : Any],
    let item = dictionary["item"] as? [AnyHashable : Any],
    let facilityAssets = item["assets"] as? [Any],
    let facilities = facilityAssets[0] as? [AnyHashable : Any],
    let asset = assets[facilities["content"]] else { return "" }

    return asset[scs_name] ?? ""
}

但是在最后一个常量中:let asset = asset [facilities [“ content”]]我得到:

  

不能用索引类型“任何”的下标“ [[AnyHashable:Any]””的值

对此有任何帮助吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试

func extractNameWithDictionary(dictionary: [String : Any]) -> String {
    guard let assets = dictionary["assets"] as? [String : Any],
          let item = dictionary["item"] as? [String : Any],
          let facilityAssets = item["assets"] as? [Any],
          let facilities = facilityAssets[0] as? [String : Any],
          let asset = assets[facilities["content"] as? String ?? "" ] as? [String:Any] else { return "" }

  return asset[scs_name] as? String ?? ""

}

facilities["content"]

返回Any,您不能在名为assets的字典中使用,因为它的密钥是AnyHashable类型

答案 1 :(得分:0)

最简单的方法是继续卸载系统,以包括内容步骤:

    ...
    let facilities = facilityAssets[0] as? [AnyHashable : Any],
    let content = facilities["content"] as? String,
    let asset = assets[content] as? [AnyHashable: String]
    else { return "" }

您可能会从那里继续收紧您的输入:

func extractNameWithDictionary(dictionary: [String : Any]) -> String {
    guard let assets = dictionary["assets"] as? [String : Any],
        let item = dictionary["item"] as? [String : Any],
        let facilityAssets = item["assets"] as? [[String : Any]],
        let content = facilityAssets.first?["content"] as? String,
        let asset = assets[content] as? [String: String],
        let name = asset[scs_name]
        else { return "" }

    return name
}

但是,当您在该项目上进行更多工作时,您将希望完全摆脱该NSDictionary,而将其替换为具有类型属性的适当结构/类,而不必执行所有这些操作as?疯狂。出现这种情况仅仅是因为使用了字典,而不是结构或类。