MaxB
MaxB

Reputation: 23

How do I check if an object on Parse is nil, in Swift?

I'm working on a swift app that allows a user to connect to and disconnect from instagram. Once the user has connected, I store the access token in the PFUser class under a column named instagramCredentials.

user["instagramCredentials"] = credentials["access_token"]
user.save()

Then if the user wants to disconnect from instagram I remove the access token.

user.removeObjectForKey("instagramCredentials")
user.save()

When the view loads I want to set a boolean, instagramIsConnected, to false unless there is an access token in instagramCredentials.

if user["instagramCredentials"] == nil {
        instagramIsConnected = false
} else {
        instagramIsConnected = true
}

but I get an error at runtime

fatal error: unexpectedly found nil while unwrapping an Optional value

What am I doing wrong?

Upvotes: 2

Views: 662

Answers (3)

Felecia Genet
Felecia Genet

Reputation: 367

swift 4 update

if (object["instagramCredentials"]) == nil {

//does not exist

} else {

//does exist

}

Upvotes: 1

Areal-17
Areal-17

Reputation: 406

you should define user["instagramCredentials"] as optional with a question mark. -> user["instagramCredentials"]?. Only optionals can be nil and than it make sense to check if a value is nil or not.

Upvotes: 0

Lucas Huang
Lucas Huang

Reputation: 4016

You should do something like this, you should learn this format of code. It's the basic of Swift:

  if let isConnected = user["instagramCredentials"] {
     instagramIsConnected = true
  } else {
     instagramIsConnected = false
  }

You can find a topic called "If Statement and Forced Unwrapping" in the Swift tutorial from Apple.

Upvotes: 2

Related Questions