swift4无法为索引为'String'的类型[[NSObject:AnyObject]'下标

时间:2018-07-20 17:37:21

标签: ios swift

我有以下方法:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    //print(userInfo)
    // Print APS.
    let aps = userInfo["aps"]
    let itemId = aps!["category"] as! String
    print("ITEM ID: \(itemId)")
    let temp = Int(itemId)
    if (temp > 0) {
        print("handle item details”)
    } else {
        print("open home")
    }
}

let aps = userInfo["aps"]行出现以下错误

  

不能用索引类型为“ String”的下标“ [NSObject:AnyObject]”的值

2 个答案:

答案 0 :(得分:2)

您可以尝试

public static Map<String, String> gsonMap2Map(JsonParser parser) throws IOException {
    ObjectCodec codec = parser.getCodec();
    TreeNode node = codec.readTree(parser);
    TreeMap<String, Double> ret = new TreeMap<String, Double>();
    if (node.isObject()) {
        for (Iterator<String> iter = node.fieldNames(); iter.hasNext();) {
            String fieldName = iter.next();
            TreeNode field = node.get(fieldName);
            if (field != null) {
                ret.put(fieldName, field.toDouble());
            } else {
                ret.put(fieldName, "null");
            }
        }
    }
    return ret;
}

//

OR

 func application(_ application: UIApplication, 
   didReceiveRemoteNotification userInfo: [AnyHashable : Any], 
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)

    if let aps = userInfo["aps"] as? [String:Any] {

    }
 }

答案 1 :(得分:1)

如果您不知道变量类型,我建议您定义变量类型。

您需要按预期的类型声明aps

let aps : [String:Any]? 

在这种情况下,如果您无法初始化aps变量,则Xcode会告诉您如何完成工作。并非总是如此,但大部分时间都是如此。