I have the following class
class BannerResponse : NSObject{
let URL = "Url";
let CONTACT_NO = "ContactNo";
let IMAGE = "Image";
let BIG_IMAGE = "BigImage";
let ID = "Id";
let TITLE = "Title";
let NO_VIEW = "NoView";
let START_DATE = "StartDate";
let END_DATE = "EndDate";
var url:String;
var contactNo:String;
var image:String;
var bigImage:String;
var title:String;
var id:Int;
var noView:Int;
var startDate:String;
var endDate:String;
init(data : NSDictionary){
url = data[URL] as! String;
contactNo = data[CONTACT_NO] as! String;
image = data[IMAGE] as! String;
bigImage = data[BIG_IMAGE] as! String;
title = data[TITLE] as! String;
id = data[ID] as! Int;
noView = data[NO_VIEW] as! Int;
startDate = data[START_DATE] as! String;
endDate = data[END_DATE] as! String;
}
}
when I run the code, I got the following error
Could not cast value of type 'NSNull' (0x10a85f378) to 'NSString' (0x109eccb20).
EDIT
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary{
onSuccess(BannerResponse(data: json))
}
} catch {
onFail()
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With