Search code examples
iosswiftcastingswift-array

Cannot subscript a value of type '[AnyObject]?' with an index of type 'UInt32'


The goal of the code below is this - get all objects from the parse.com class called OnlineUsers and then find a RANDOM number between 0 and results.count and then use that object for something.

Issue is that when I try to get the object at position results[randomNumber], I get the error below. I get the same error if I try results[randomNumberCast] below.

How can I solve this problem?

func findRandomOnlineUser() {
    if PFUser.currentUser() != nil {
        var user1 = PFUser.currentUser()
        var user2 = PFUser()



        //find user2, i.e. some user who is online right now
        //Showing OnlineUsers only
        let onlineUsersQuery = PFQuery(className: "OnlineUsers")
        onlineUsersQuery.findObjectsInBackgroundWithBlock({ (results:[AnyObject]?, error:NSError?) -> Void in

            if results!.count > 0 {
                self.mLog.printToLog("launchChatwithRandomUser() -- There are more than zero objects in OnlineUsers")

                //help: http://stackoverflow.com/questions/26770730/apple-swift-placing-a-variable-inside-arc4random-uniform
                let randomNumber = arc4random_uniform(UInt32(results!.count))
                var randomNumberCast = Int(randomNumber)

                if let userObject = results[randomNumberCast] {
                    user2 = userObject["user"] as! PFUser
                } else {
                    //handle the case of 'self.objects' being 'nil'
                }

    } else {
        //TODO: Show a prompt that user is not logged in and then take user to Login Screen
    }


}

Error Message:

Screenshot showing the error message


Solution

  • the fact that results seems to be an optional array: [AnyObject]?. Therefore, if you want to access one of its values via a subscript, you have to unwrap the array first:

    if let userObject: AnyObject = results?[randomNumberCast]