1
votes

Ok so I am trying to run this code but I keep on getting this error: fatal error: unexpectedly found nil while unwrapping an Optional value. I don't understand what it means or why im getting it. Can someone please help me. Thanks

query.whereKey("accepted", equalTo: PFUser.currentUser().username)
query.whereKey("username", containedIn: PFUser.currentUser()["accepted"] as [AnyObject])
2
This means that the program is receiving nil value for a optional variable. Please check for nil and then do the next operation. I am guessing "PFUser.currentUser()" might be returning nil.rshankar

2 Answers

0
votes

According to objective-c documentation of PFUser.currentUser(), which I'm assuming translates into a Swift optional, it could easily return nil. So you need to do something like:

if let currentUser = PFUser.currentUser() {
    query.whereKey("accepted", equalTo: currentUser.username)
    if let someArrayObject = currentUser["accepted"] as? [AnyObject] {
        query.whereKey("username", containedIn: someArrayObject)
    }
} else {
    // currentUser does not exist, do error handling
}

Not sure what that second query line is, and what the someArrayObject is, so you might look further into that. But your error is either related to you dereferencing the currentUser() which could be nil, or the use of as and not as? in the second query line.

Solution to either is to use proper unwrapping of the potential optional values.

0
votes

All you have to do is this:

if let currentUser = PFUser.currentUser() {
    query.whereKey("accepted", equalTo: currentUser.username)
    if let someArrayObject = currentUser["accepted"] as? [AnyObject] {
        query.whereKey("username", containedIn: someArrayObject)
    }
} else {
    // currentUser does not exist, do error handling
}