Can't tweak a value of type "[AnyObject]?" with an index of type 'UInt32'
The purpose of the code below is to get all the objects from the parse.com class called OnlineUsers
and then find the RANDOM number between 0
and results.count
and then use that object for something.
The problem is that when I try to get the object in position results[randomNumber]
, I get the below error. I am getting 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:
+3
source to share