Reputation: 1081
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) ...
Upvotes: 0
Views: 6632
Reputation: 79
Try something like this:
if let category = Stream["vote_status"] as? String {
print(category)
} else {
print(category)
}
Upvotes: 1
Reputation: 236315
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"
Upvotes: 6
Reputation: 3385
You can try this
func checkForNull(value:AnyObject) -> String
{
if(value as! NSObject == NSNull() || value as! String == "")
{
return " "
}
else
{
return value as! String
}
}
Upvotes: 1
Reputation: 5451
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
Upvotes: 1