Snap Kit Login Kit Error (Swift)

490 Views Asked by At

Copying the documentation gets me a "Type '[AnyHashable : Any]?' has no subscript members. The error happens on the "let data = " line. If I force unwrap resources, then the error moves to the next line

let graphQLQuery = "{me{displayName, bitmoji{avatar}, externalId}}"
    let variables = ["page": "bitmoji"]

    SCSDKLoginClient.fetchUserData(withQuery: graphQLQuery, variables: variables, success: { (resources: [AnyHashable: Any]?) in
        let data = resources["data"] //error here
        let me = data["me"]
        let displayName = me["displayName"]
        let bitmoji = me["bitmoji"]
        let bitmojiAvatarUrl = bitmoji["avatar"]
    }, failure: { (error: Error?, isUserLoggedOut: Bool) in
        // handle error
    })

If I unwrap data resources and data, then the error moves to the line where I try to set me = data["me"] (error = "Type Any has no subscript members"). Then if I try to unwrap me, the error remains.

ex:

let graphQLQuery = "{me{displayName, bitmoji{avatar}, externalId}}"

let variables = ["page": "bitmoji"]

        SCSDKLoginClient.fetchUserData(withQuery: graphQLQuery, variables: variables, success: { (resources: [AnyHashable: Any]?) in
            guard let response = resources else { return }
            guard let data = response["data"] else { return }
            print(data)
            let me = data["me"] // error here
            let displayName = me["displayName"]
            let bitmoji = me["bitmoji"]
            let bitmojiAvatarUrl = bitmoji["avatar"]
        }, failure: { (error: Error?, isUserLoggedOut: Bool) in
            // handle error
        })

Printing out data returns:

{
    me =     {
        bitmoji =         {
            avatar = "{URL}";
        };
        displayName = "{NAME}";
        externalId = "{ID}";
    };
}
1

There are 1 best solutions below

2
On

That's because [AnyHashable: Any]? is optional thats why it's giving an error

"Type '[AnyHashable : Any]?' has no subscript members

So for that you need to wrap it with if let condition as shown below:

if let response = resources {
    let data = response["data"] //then cast your objects here
}

Or you can use guard let for that:

guard let response = resources else { return }

after that you can use response object.