我想使用 swift 中的循环将项目附加到数组中。
我的代码如下所示,我看到此错误:
For-in loop requires 'JSON?' to conform to 'Sequence'; did you mean to unwrap optional?
在下面的代码中,我想将每封电子邮件添加到类中定义的数组中:
func loadData() {
Alamofire.request(URL, method: .get)
.responseSwiftyJSON { dataResponse in
let response = dataResponse.value
for item in response { // For-in loop requires 'JSON?' to conform to 'Sequence'; did you mean to unwrap optional?
print(item)
// ideally I want to push the email here
// something like emails.append(item.email)
}
if let email = response?[0]["email"].string{
print(email) // This shows correct email
}
}
}
谁能告诉我这里的解决方案是什么?
最佳答案
此处的错误是 dataResponse.value
是 JSON,因此为了使用 value
属性,您必须对其进行强制转换。
所以你的代码应该是这样的:
func loadData() {
Alamofire.request(URL, method: .get)
.responseSwiftyJSON { dataResponse in
guard let response = dataResponse.value as? [String: Any] else {
print("error in casting")
return
}
for item in response { // For-in loop requires 'JSON?' to conform to 'Sequence'; did you mean to unwrap optional?
print(item)
// ideally I want to push the email here
// something like emails.append(item.email)
}
if let email = response?[0]["email"].string{
print(email) // This shows correct email
}
}
}
我将其转换为字典,因为 JSON 响应大多数时候都是字典。我还建议您使用 Swift Codables 来映射您的 json 响应。引用这里:https://www.hackingwithswift.com/articles/119/codable-cheat-sheet
关于ios - For-in 循环需要 'JSON?' 才能符合 'Sequence' ;你的意思是打开可选的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65507691/