Rorschach
Rorschach

Reputation: 3802

Check if JSON as dictionary contains Optional(null)

I want to make an if statement that checks if my JSON (item_section) has a null value at a certain key.

This code:

let my_dict = item_section[counter].dictionaryValue
print(my_dict["creator"])

prints: Optional(null) when the creator is not set.

If it is set if it prints the creator's name, like: user_729834892.

How can I make an if statement that checks if the creator is null?

Such as:

if ((my_dict["creator"]) == nil) {  //This line does not work
    my_dict["creator"] = "No Maker"
}

Upvotes: 0

Views: 101

Answers (3)

Sulthan
Sulthan

Reputation: 130102

The JSON framework never returns an optional when indexing a dictionary (a JSON object). If the value doesn't exist, it rather returns the constant JSON.null, which you can compare:

if my_dict["creator"] == JSON.null {
    my_dict["creator"] = "No Maker"
}

also method isExists would work

if !my_dict["creator"].isExists() {
    my_dict["creator"] = "No Maker"
}

Upvotes: 0

Pratik
Pratik

Reputation: 433

try this

    print( my_dict.indexForKey( "creator") )

    if (my_dict.indexForKey( "creator") == nil) {

        my_dict["creator"] = "No Maker"
    }

if the creator is not set then function indexForKey will return nil.

Upvotes: 0

Code
Code

Reputation: 6251

Try

if my_dict["creator"].type == .Null {
    print("creator is null")
}

Upvotes: 1

Related Questions