swift how can I check for NULL values coming from

2019-06-14 18:47发布

问题:

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

回答1:

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"


回答2:

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 


回答3:

You can try this

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


回答4:

Try something like this:

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