我想在want中使用循环将项附加到数组中。
我的代码如下所示,我看到了这个错误:
For-in循环需要'JSON?‘若要符合“序列”,您是指可选地展开吗?
在下面的代码中,我希望将每个电子邮件添加到类中定义的数组中:
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
}
}
}
有人能告诉我解决办法是什么吗?
发布于 2020-12-30 13:34:16
这里的错误是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
https://stackoverflow.com/questions/65507691
复制相似问题