I am playing With JSON for last two days and facing alot of curious problems and thanks to stack overflow it helps me. This is JSON featured key has two types of String values.
"featured":"1"
or
"featured": null,
I tried a lot to handle this but failed
Step 1:
if dict.objectForKey("featured") as? String != nil {
featured = dict.objectForKey("featured") as? String
}
Step 2:
let null = NSNull()
if dict.objectForKey("featured") as? String != null {
featured = dict.objectForKey("featured") as? String
}
Step 3:
if dict.objectForKey("featured") as? String != "" {
featured = dict.objectForKey("featured") as? String
}
but unfortunately can't found solution, you answer will be appreciated.
Try this!
Optional chaining with
if let
or its counterpartguard let
is the way to go. All three steps combined (missing, wrong type - NSNull too, empty string):If you want to know more about optional chaining check out documentation
i did a static func to convert value from json to optional String.
In my controller
i'm open to your feedback
Here is a working code, type cast operator(as?) will do the trick here. Null will not be typecasted into String, so the execution will go to failure block.
Try This
Here, you can use this method, which will convert null value to nil and wont' cause crash in your app.
You can also use as?
Thanks.
Hi you can use below function to remove null to empty string and prevent crashes
and before giving dict to any method call function in below way