I have the following class
class BannerResponse : NSObject{
let URL = \"Url\";
let CONTACT_NO = \"ContactNo\";
let IMAGE
One of your data[SOME_KEY]
is of type NSNull
instead of String
and because you're forcing the cast to String
by using !
the app crashes.
You can do one of two things:
?
instead of !
when setting the values in your init
method. Like this:`
var title: String?
init(data: NSDictionary)
{
self.title = data[TITLE] as? String
}
or
?
instead of !
when setting the values in your init
method but set a default value whenever dict[SOME_KEY]
is nil or is not the expected type. This would look something like this:`
if let title = data[TITLE] as? String
{
self.title = title
}
else
{
self.title = "default title"
}
// Shorthand would be:
// self.title = data[TITLE] as? String ?? "default title"
And I guess a third thing is ensure that the server never sends down null values. But this is impractical because there's no such thing as never. You should write your client-side code to assume every value in the JSON can be null or an unexpected type.
You are getting null values for some of your keys. They get mapped to NSNull by NSJSONSerialization.
You need to do several things
Change all your variables (url
, contactNo
, etc) to optionals:
var url:String?
var contactNo:String?
Change all of your assignments to use ?
instead of !
:
url = noNulls[URL] as? String
contactNo = noNulls[CONTACT_NO] as? String
And finally, make your code handle nil values for all of your variables. (But do not use !
. That path leads to crashes.)