Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast from 'JSON' to unrelated type 'String' always fails [duplicate]

Tags:

ios

swift

Currently I'm using SwiftyJSON to convert the data set into JSON type.

When I run this: print(json), it will print on the Xcode console.

{
  "user_id": "123999923821" 
}

But whenever I try to do execute json["user_id"] as? String, it always returns nil.

socketManager.socket.on("toAllDrivers") { data, ack in
            if let vc = self.storyboard?.instantiateViewController(withIdentifier: "PopViewControllerID") as? PopUpViewController {

                let json = JSON(data[0])
                print(json)
                vc.passenger_id = json["user_id"] as? String // This is the line of code that return a problem.

                self.present(vc, animated: true, completion: nil)
            }


        }

vc.passenger_id is a type String:

var passenger_id: String?

The error is:

Cast from 'JSON' to unrelated type 'String' always fails

What should I do to fix this?

like image 567
sinusGob Avatar asked Oct 15 '25 23:10

sinusGob


2 Answers

You should use SwiftyJSON's built in String converter to convert the value to an optional String.

vc.passenger_id = json["user_id"].string
like image 124
Tamás Sengel Avatar answered Oct 17 '25 14:10

Tamás Sengel


Try this: (without using SwiftyJSON and it should work)

if let json = JSON(data[0]) as? [String : Any] {
   vc.passenger_id = json["user_id"] as? String
}

or

if let user_id = json["user_id"] as? String {
   vc.passenger_id = user_id
   print("user_id- \(user_id)")
}
print("vc.passenger_id - \(vc.passenger_id)")
like image 40
Krunal Avatar answered Oct 17 '25 14:10

Krunal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!