[英]For-in loop requires 'JSON?' to conform to 'Sequence'; did you mean to unwrap optional?
I want to append items to an array using a loop in swift.我想使用 swift 中的循环将 append 项添加到数组中。
My code looks like the following and I am seeing this error:我的代码如下所示,我看到了这个错误:
For-in loop requires 'JSON?'
For-in 循环需要“JSON?” to conform to 'Sequence';
符合“顺序”; did you mean to unwrap optional?
你的意思是解开可选的吗?
In the code below I want to add each email to an array defined in the class:在下面的代码中,我想将每个 email 添加到 class 中定义的数组中:
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
}
}
}
Can anyone advise what the solution is here?谁能建议这里的解决方案是什么?
The error here is that dataResponse.value
is JSON so in order to use the value
property you have to cast it.这里的错误是
dataResponse.value
是 JSON 所以为了使用value
属性,你必须转换它。
So your code should look like that:所以你的代码应该是这样的:
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
}
}
}
I cast as dictionary because JSON responses most of the times are dictionaries.我将其转换为字典,因为 JSON 响应大多数时候都是字典。 I also suggest you to use Swift Codables in order to map your json responses.
我还建议您使用 Swift Codables 来 map 您的 json 响应。 reference here: https://www.hackingwithswift.com/articles/119/codable-cheat-sheet
参考这里: https://www.hackingwithswift.com/articles/119/codable-cheat-sheet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.