我有以下课程
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; } }
Could not cast value of type 'NSNull' (0x10a85f378) to 'NSString' (0x109eccb20).
编辑
do { if let json = try NSJSONSerialization.JSONObjectWithData(data!,options: NSJSONReadingOptions.MutableContainers) as? NSDictionary{ onSuccess(BannerResponse(data: json)) } } catch { onFail() }
解决方法
你的一个数据[SOME_KEY]的类型是NSNull而不是String,因为你正在使用强制转换为String!该应用程序崩溃.
你可以做以下两件事之一:
>将BannerResponse类的变量更改为可选.用吗?代替 !在init方法中设置值时.像这样:
`
var title: String? init(data: NSDictionary) { self.title = data[TITLE] as? String }
要么
>使用?代替 !在init方法中设置值但在dict [SOME_KEY]为nil或不是预期类型时设置默认值.这看起来像这样:
`
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"
我想第三件事是确保服务器永远不会发送空值.但这是不切实际的,因为从来没有这样的事情.您应该编写客户端代码,以假设JSON中的每个值都可以为null或意外类型.