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?
You should use SwiftyJSON
's built in String converter to convert the value to an optional String
.
vc.passenger_id = json["user_id"].string
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)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With