Could not cast value of type 'NSNull' to 'NSString' in parsing Json in swift

前端 未结 2 1181
一生所求
一生所求 2021-02-04 12:07

I have the following class

class BannerResponse : NSObject{

    let  URL                = \"Url\";
    let  CONTACT_NO         = \"ContactNo\";
    let  IMAGE          


        
2条回答
  •  青春惊慌失措
    2021-02-04 12:28

    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:

    1. Change your variables on the BannerResponse class to be optional. And use ? 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

    1. Use ? 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.

提交回复
热议问题