For-in 循环需要"JSON?"以符合"序列";你的意思是解开可选包装吗?



我想使用swift中的循环将项附加到数组中。

我的代码看起来如下,我看到了这个错误:

For在循环中需要"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
}
}
}

有人能告诉我们这里的解决方案吗?

这里的错误是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
}
}
}

我选为dictionary,因为JSON响应大多数时候都是dictionary。我还建议您使用Swift Codables来映射json响应。此处引用:https://www.hackingwithswift.com/articles/119/codable-cheat-sheet

相关内容

最新更新