Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 627
Eli Braginskiy Avatar asked Dec 26 '22 04:12

Eli Braginskiy


2 Answers

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
        }
    }
like image 91
ChikabuZ Avatar answered Jan 14 '23 12:01

ChikabuZ


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.

like image 40
Fogmeister Avatar answered Jan 14 '23 13:01

Fogmeister