user1079052 user1079052 - 2 months ago 51
Swift Question

Ambiguous reference to subscript with string literal and NSObject subscript type

I am upgrading my project to swift 3.0 and I am getting an error on userInfo["aps"]. I have tried putting a question mark and explanation point between it but no luck

private func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

if let aps = userInfo["aps"] as? NSDictionary {
if let alert = aps["alert"] as? NSDictionary {
if let message = alert["message"] as? NSString {
//Do stuff
}
} else if let alert = aps["alert"] as? NSString {
//Do stuff
}
}


}

Answer

As always, use Swift collection types, the Foundation collection types don't provide any type information about their contents.

First of all use the actual signature of the delegate method, marking the method as private and keeping the old signature is a bad compromise. However consider that the method is deprecated.

func application(_ application: UIApplication, didReceiveRemoteNotification 
                      userInfo: [AnyHashable : Any])

The JSON collection types are always [String:Any] (dictionary) or [[String:Any]] (array)

func application(_ application: UIApplication, didReceiveRemoteNotification 
                      userInfo: [AnyHashable : Any])

    if let aps = userInfo["aps"] as? [String:Any] {
        if let alert = aps["alert"] as? [String:Any] {
            if let message = alert["message"] as? String {
                //Do stuff
            }
        } else if let alert = aps["alert"] as? String {
            //Do stuff
        }
    }
}