YogeshChauhan . com

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!"
}
amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

bin2hex() and chr() String Functions in PHPPHPAdd animated hamburgers menu using Hamburgers collection on GitHubCSSHow to use GROUPING SETS to boost GROUP BY queries in Postgres?PostgresCustom Post Type Template Files in WordPressWordPressValues and Types Basics in JavaScriptJavaScriptAn Example of Cross-site Scripting (XSS) Attack in PHP and How to Avoid It?PHPRendering Elements in ReactReactHow to create a simple digital clock using JavaScript?JavaScriptArguments in @mixin rules in SCSS (Sass)SCSSHow to create rotating texts using JavaScript and CSS?CSSWhat is iFrame in HTML? Why do we need it?HTMLHow to hide a DIV on clicks outside of it using jQuery?jQuery