简体   繁体   中英

swift 3: Type 'Any?' has no subscript members

I keep getting this error for my graph requests??

Type 'Any?' has no subscript members

the error points at result.... this only happened when I converted to swift 3... anybody????

 let nextrequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/friends", parameters: ["fields": "name, id, gender"], httpMethod: "GET")
            nextrequest.start { (connection, result, error) -> Void in
                guard let listOfFriends = result["data"] as? [AnyObject] else {
                    return
                }
            }
        }

Try this

let nextrequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath:"me/friends", parameters: ["fields": "name, id, gender"], httpMethod: "GET")
    nextrequest.start { (connection, result, error) -> Void in
         guard let result = result as? [String:[AnyObject]], let listOfFriends = result["data"]  else {
        return
    }
  }
}

A little explanation

In Swift 3, the Value type of NSDictionary, NSArray, etc. have been changed to Any. So the result type of subscript result[key] is Any?, which cannot be automatically converted to AnyObject.

You have to explicitly cast into [String:[AnyObject]] type before using the result.

Try using,

let tResult = result as? [String:[AnyObject]]
guard let listOfFriends = tResult["data"] else { return; }

as mentioned in the answer of @xhmar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM