swift how can I check for NULL values coming from

2019-06-14 18:51发布

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条回答
干净又极端
2楼-- · 2019-06-14 19:30

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"
查看更多
贼婆χ
3楼-- · 2019-06-14 19:34

Try something like this:

if let category = Stream["vote_status"] as? String {
                        print(category)
                    } else {
                        print(category)
                    }
查看更多
再贱就再见
4楼-- · 2019-06-14 19:36

You can try this

func checkForNull(value:AnyObject) -> String
    {
        if(value as! NSObject == NSNull() || value as! String == "")
        {
           return " "
        }
        else
        {
            return value as! String
        }
    }
查看更多
Fickle 薄情
5楼-- · 2019-06-14 19:54

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 
查看更多
登录 后发表回答