swift how can I check for NULL values coming from Json

6.3k views Asked by At

I have a rest api and am getting all data via Json then putting it in a IOS TableView. My issue is that some data is being returned as NULL in Json

"vote_status":null

I am trying to get that NULL value in swift and change it to a string "0" but am having a hard time doing so . I have this so far

  if var vote_status = Stream["vote_status"] as? String {
                                if (vote_status == (vote_status)[NSNull]) {
                                   vote_status = "0"
                                }
}

However I get this compile error:

Cannot subscript a value of type 'String' with an index of type '(NSNull).Type' (aka 'NSNull.Type')

I am doing this because nil and null does not seem to work so I can't do this.

if (vote_status == nil) ...
4

There are 4 answers

0
Leo Dabus On BEST ANSWER

You just need to conditionally cast your dictionary value to String and use the Nil Coalescing Operator ?? to assign "0" in case of failure null:

let vote_status = Stream["vote_status"] as? String ?? "0"
0
Harshal Valanda On

Swift 3.0

func checkNull(obj : AnyObject?) -> AnyObject? {
    if obj is NSNull {
        return nil
    } else {
        return value
    }
}

object.feature = checkNull(dict["feature"])

try this

vote_status is NSNull 
0
Vinod Kumar On

You can try this

func checkForNull(value:AnyObject) -> String
    {
        if(value as! NSObject == NSNull() || value as! String == "")
        {
           return " "
        }
        else
        {
            return value as! String
        }
    }
0
Dr.Drakeson On

Try something like this:

if let category = Stream["vote_status"] as? String {
                        print(category)
                    } else {
                        print(category)
                    }