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 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

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 find the HCF or GCD and LCM of two given numbers using Swift?SwiftThe ALPHA function in Envision BasicEnvision BasicHow to control file extensions with an .htaccess file?MiscellaneousHow to test the WordPress 5.9 Beta 4?WordPressHow to CREATE TABLE in SQL with and without using Another Table?SQL/MySQLHow to define visibility for a property in PHP?PHPHigher Order Functions in JavaScript with ExamplesJavaScriptHow to add before after image effect using pure CSS?CSSHow to create a dynamic countdown using HTML and JavaScript?HTMLHow does Next.js load pages faster?NextJSClean Form Input With These PHP Functions Before Inserting into DatabasePHPHow to create two segues with two UIButtons on a single page (Swift 5.0)?Swift