Yogesh Chauhan's Blog

Solution to Could not cast value of type ‘NSTaggedPointerString’ to ‘NSNumber’

in Swift on May 5, 2020

Whenever you try to get responses from API, you get the JSON response in most cases and this error occurs all the time while getting the value from JSON array or dictionary as Int or as NSNumber.

In many cases (NOT ALL), the reason of the error is the JSON data we get is a String (Note: NSTaggedPointerString is a subclass of NSString).

So what we can do is to convert String to Double.

Like this:


// check dict["dummy"] is a String first
if let receivedData = (dict["dummy"]).doubleValue {
  // add more code in case the condition is true
}
else {
 // add more code in case the condition is false
}

OR


// check dict["dummy"] is a String first
if let receivedData = (dict["dummy"] as? NSString)?.doubleValue {
  // add more code in case the condition is true
}
else {
 // add more code in case the condition is false
}

Both of those solutions work.

It is really helpful when you want to compare the received data or just check the value like the following example.


let receivedData = (results["data"]!).doubleValue

if (receivedData == 0){
      self.label.text = "Nothing seem to be added yet!"
}

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to add a ribbon inside a container using CSS?CSSHow to use PHPMailer to send an Email via Gmail SMTP Server?PHPHow to add today’s date in HTML input date value using JavaScript?JavaScriptWordPress: How to get field values in Advanced Custom Fields?WordPressHow to create rotating texts using JavaScript and CSS?CSSHow to Hide HTML elements automatically after few seconds using JavaScript?HTMLHow to read Standard Input in Swift?SwiftFor In Loop in Swift for BeginnersSwiftHow to Use Aggregate Functions (MIN, MAX, SUM, AVG, COUNT) to Summarize Data in SQL?SQL/MySQLHow to check if radio button is checked or not using JavaScript?JavaScriptHow to list all PHP variables to debug the script?PHPHow to load a module with configuration in SCSS?SCSS