David Seek David Seek - 2 months ago 9
Swift Question

Swift / how to check for existence of optional value

I'm having an

Array
of
NSDictionary
named
deejayTweetsDictionary
. Within the optional Key
likes
is an
Array
of
NSDictionary
.

Now I want to check if:
user == likes?.valueForKey(user) as! String
.

My Code works fine as long as
user
is within
likes
. If I login with another account - with another
user
, the app crashes on:

if likes?.valueForKey(user) as! String == user {


How can I check my if statement if
likes
is optional and is able to contain different
user
NSDictionaries
?

let tweets = deejayTweetsDictionary[indexPath.row]

let likes = tweets.valueForKey("likes")
let user = backendless.userService.currentUser.objectId

if likes != nil {

if likes?.valueForKey(user) as! String == user {
cell.liked = 1
} else {
cell.liked = 0
}
}


enter image description here

Again:
likes
may contain an infinity number of
[user:user]


Question: How do I check my if statement in case
user
is not within
likes
? Help is very appreciated.

Answer

The crash is because of forced unwrap in the line

if likes?.valueForKey(user) as! String == user {

Try this way:

if let userExist = likes?.valueForKey(user) as? String where userExist == user {

       //Do your work.
}

You have to use this optional binding or guard keyword.