下面代码的目标是这样 - 从名为OnlineUsers
的parse.com类中获取所有对象,然后在0
和results.count
之间找到一个RANDOM编号,然后使用该对象为了某事。
问题是,当我尝试将对象放在位置results[randomNumber]
时,我收到以下错误。如果我在下面尝试results[randomNumberCast]
,我会收到相同的错误。
我该如何解决这个问题?
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
}
}
错误讯息:
答案 0 :(得分:6)
results
似乎是一个可选数组:[AnyObject]?
。
因此,如果要通过下标访问其中一个值,则必须首先解包该数组:
if let userObject: AnyObject = results?[randomNumberCast]