I have this JSON data that I just parse with JSONDecoder. I have made a struct to decode this JSON data and I want this value from that JSON to be a global variable so I can pass it to other controller. I already make this global variable and I just want to put my JSON variable into this global variable.
Since it's an Int
and my global variable is a string
, so I'm trying to convert it first with : var a = string(jsonvalue)
, but I get this error:
Initializer
'init(_:)'
requires that'[_]'
conform to 'LosslessStringConvertible'
All of this I search it from web, I'm still a junior developer so I need your help please to finish my project.
this is my global variable :
struct GlobalVariable {
static var ProjectId = String() //project id
static var UserId = String() // User Id
var GroupId = String() // group Id
static var Status = String() //Status for login
init(dictionary : [String : Any]) {
id = dictionary ["id"] as! Int
name = dictionary ["name"] as! String
email = dictionary ["email"] as! String
status = dictionary ["status"] as! String
}
enum CodingKeys : String, CodingKey {
case id = "id"
case name = "name"
case email = "email"
case status = "status"
}
}
}
var Loginnn = [login]()
struct login : Codable {
let id : Int
let name : String
let email : String
let status : String
}
let parsing = try JSONDecoder().decode([login].self, from: data)
print(parsing)
self.Loginnn = parsing
//This is for login verification
let stats = self.Loginnn.map { $0.status}
//this is the Id value I try to make into global Variable
let ids = self.Loginnn.map { $0.id} // I use this map function to extract that value and put it into the variable
GlobalVariable.UserId = String(ids)// I use string to convert from int to string. --> this is where the error begin
if stats.contains("1"){ // Login Success
print("Login Success")
DispatchQueue.main.async {
self.appDelegate.loginSeque()
}
}else if stats.isEmpty {//fail login
let action = UIAlertAction(title: "Got It", style: .default, handler: nil)
let alert = UIAlertController(title: "Wrong Email / Password", message: "Please Try Again ", preferredStyle: .alert)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}catch{
print(error)
}
}.resume()
from that line of code : let ids = self.Loginnn.map { $0.id}
, I am able to get that id value from JSONDecoder
, but when I try to put it into the global variable it shows error like this:
Initializer
'init(_:)'
requires that'[_]'
conform to 'LosslessStringConvertible'
I need help, because I'm still a junior developer, so I don't know if this code is correct or not.
Assuming you only get one row back in your json message, or only the first one is interesting you can do
if let id = ids.first {
let GlobalVariable.UserId = String(id)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.