Eli Waxman
Eli Waxman

Reputation: 2897

can't unwrap optional in swift

I'm using Parse, and getting a PFUsers objectId like so:

let objectID = PFUser.currentUser().objectId;

but every time I run my app and the app gets to this line I get this:

fatal error: unexpectedly found nil while unwrapping an Optional value

and if I try to change to this:

let objectID = PFUser.currentUser().objectId!;

I can't do this next line :if (objectID != nil) because NSString doesn't conforms to NiLiteralConvertible

Upvotes: 4

Views: 712

Answers (2)

ChikabuZ
ChikabuZ

Reputation: 10185

Try this:

    let user: PFUser? = PFUser.currentUser()
    if user != nil
    {
        let objectID = user!.objectId
    }

or if objectId can be nil:

    let user: PFUser? = PFUser.currentUser()
    if user != nil
    {
        if let objectID = user!.objectId?
        {
            //do something
        }
    }

Upvotes: 7

Fogmeister
Fogmeister

Reputation: 77641

The optional here is the return value from PFUser.currentUser() not the objectId.

You need change this slightly as it may be possible that the current user doesn't exist.

Something like...

if let user = PFUser.currentUser()! {
    let objectID = user.objectId
}

or something. Not quite sure though as I haven't got into Swift properly yet.

Upvotes: 3

Related Questions