swift - 将函数映射到快速错误中的全局变量“初始化程序'init(_:)'要求'[_]'符合'LosslessStringConvertible'”
问题描述
我有这个 JSON 数据,我只是用 JSONDecoder 解析。我已经制作了一个结构来解码这个 JSON 数据,我希望该 JSON 中的这个值是一个全局变量,这样我就可以将它传递给其他控制器。我已经创建了这个全局变量,我只想将我的 JSON 变量放入这个全局变量中。
由于它是 anInt
并且我的全局变量是 a string
,所以我尝试先将其转换为 : var a = string(jsonvalue)
,但出现此错误:
Initializer
'init(_:)'
要求'[_]'
符合 'LosslessStringConvertible'
所有这些我都是从网上搜索的,我仍然是一名初级开发人员,所以我需要你的帮助来完成我的项目。
这是我的全局变量:
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()
从那行代码 : let ids = self.Loginnn.map { $0.id}
,我可以从中获取该 id 值JSONDecoder
,但是当我尝试将其放入全局变量时,它会显示如下错误:
Initializer
'init(_:)'
要求'[_]'
符合 'LosslessStringConvertible'
我需要帮助,因为我还是初级开发人员,所以我不知道这段代码是否正确。
解决方案
假设您在 json 消息中只得到一行,或者只有第一行是有趣的,您可以做
if let id = ids.first {
let GlobalVariable.UserId = String(id)
}
推荐阅读
- windows - 如何迭代或循环匹配特定条件的文件夹
- javascript - 这个reduce函数能写得更高效吗?
- sql - 如何使用 linq lambda 扩展方法执行带有 where 子句的左外连接
- sql - 如何使用标准 SQL BIG Query 语法在不重复的情况下重写它?
- kotlin - Kotlin:无法在 Arraylist 中找到元素
- excel - 一种在合并单元格中查找字符串的方法
- python - 如何测试不同格式的日期和日期时间?
- javascript - 如何根据属性移动类
- powershell - 如何运行“Get-Command”返回的所有 cmdlet?
- c# - 为什么四分之三的非常相似的 ajax 调用作为帖子工作,而第四个只作为 get 工作?