Could Not Cast Value of Type 'Nsnull' (0X10Aa1B600) to 'Nsstring' (0X10B4Dab48)

Could not cast value of type 'NSNull' (0x10aa1b600) to 'NSString' (0x10b4dab48)

use if let or guard statement to check dict["googlepluslink"] is String or not and then according to that you can append your data like below

if let link = dict["googlepluslink"] as? String 
{
self.googlepluslink.append(link)
}
else {
self.googlepluslink.append("-")
}

Could not cast value of type 'NSNull' to 'NSString'

Well, they tell you what the problem is: You've got a result of type NSNull, and NSNull cannot be converted to NSString.

Most likely you are processing JSON, and JSON data often contains null values.

Go away from your labyrinth of ? and !

Write some code that helps you. Remember that any ! will crash your application if you don't get what you expect.

When you access the key "name" in a dictionary, you need to handle the case that there is a string (nice for you), nothing (key doesn't exist, very common), null (the server tells you explicitly that there is nothing, very common), a number, bool, dict or array.

For each of these cases, tell me what you want as a result: A crash? An optional string that is nil? An empty string? Typically you want a string if it is there, possibly a number converted to a string if it is a number, and either nil or an empty string if the key isn't there or null, and either a crash or nil if you get a bool, dictionary or array.

Then write a function that returns exactly that. And then you use it. When you write (... as? NSString)! you tell the compiler that you want a crash if it's not a string, and that's what you got.

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

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.



Related Topics



Leave a reply



Submit