Search code examples
jsonswiftswift3nsnull

swift how can I check for NULL values coming from Json


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) ...

Solution

  • 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"