-3

here is the bit of code giving me the issue:

func loadUrl(_ obj:AnyObject?){

        let urlObj = obj as! NSDictionary
        let urlPath = urlObj["aps"]!["alert"] as! String
        let requestUrl = URL(string: urlPath)
        let request = URLRequest(url: requestUrl!)
        webView.loadRequest(request)

Tried many of the things posted but none work in my case, any heal is greatly appreciated!

  • Simply ask you this: Who told the compiler that the object `urlObj["aps"]` can be used with subscript by writing `["alert"]` after it (ie doing `urlObj["aps"]!["alert"]`) ? No one. That's what the errors means. `urlObj["aps"]` is of type `Any`, and `Any` by defaults have no subscript, so you can do `anAnyObject["aps"]`. Cast it before. – Larme Apr 18 '17 at 16:12
  • 2
    Please search on your error. This [has been asked many times before](http://stackoverflow.com/search?q=%5Bswift%5D+type+%27Any%27+has+no+subscript+members). – rmaddy Apr 18 '17 at 16:16
  • FYI - every use of `!` in your code means "crash here". – rmaddy Apr 18 '17 at 16:25

1 Answers1

0

In Swift 3 the compiler needs to know the types of all subscripted objects.

And it's highly recommend to unwrap the optionals safely:

func loadUrl(_ obj: Any?) {

    if let urlObj = obj as? [String:Any],
       let aps = urlObj["aps"] as? [String:Any],
       let urlPath = aps["alert"] as? String,
       let requestUrl = URL(string: urlPath) {
          let request = URLRequest(url: requestUrl)
          webView.loadRequest(request)
     ...
     }

Please read also Larme's comment.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Side note, since you didn't write it, in Swift 3, prefers Swift Dictionaries rather than NSDictionary, and Any rather than AnyObject, no? – Larme Apr 18 '17 at 16:16
  • @Larme Thanks, I wrote that already a countless times in countless comments / answers. – vadian Apr 18 '17 at 16:18
  • 3
    There must be several duplicates for this question. Why post yet another answer? – rmaddy Apr 18 '17 at 16:24
  • @rmaddy Because most of the *code copy-pasters* are already overstrained if the keys and types in the answers are slightly different ;-) And the answer is also a hint how to properly unwrap optionals. – vadian Apr 18 '17 at 16:27
  • 1
    What about your own [answer here](http://stackoverflow.com/a/39423764/1226963)? – rmaddy Apr 18 '17 at 16:34