skip to Main Content

I have the following code.

func setUserToken(_ user: NSDictionary) {
    self.userId = user["user"]["id"] as! String;

I get the error "Value of type Any has no subscripts". What am I doing wrong?

2

Answers


  1. The type of any lookup from a NSDictionary is Any. You know (or think you know) it is another dictionary, but Swift does not. You must establish the type before you can do the second lookup.

    func setUserToken(_ user: NSDictionary) {
        if let userDict = user["user"] as? NSDictionary {
            // We now know “user” is a valid key and its value
            // is another NSDictionary
     
            if let userId = userDict["id"] as? String {
                // We now know “id” is a valid key and its
                // value is of type String which has been
                // assigned to userId.  Now assign it to the
                // property
                self.userId = userId
                return
            }
        }
    
        // If we get here, something went wrong.
        // Assign a reasonable default value.
        self.userId = “user unknown”
    }
    

    You can do it in a single line using optional chaining and the nil coalescing operator:

    self.userId = ((user["user"] as? NSDictionary)?["id"] as? String) ?? “user unknown”
    
    Login or Signup to reply.
  2. You need to specify your json before parsing it. Try This:

    func setUserToken(_ user: NSDictionary) {    
        guard let userData = user as? NSDictionary else{return}
        guard let user = userData["user"] as? String else{return}
        self.userid = user["id"] as? String else{return}
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search