【发布时间】:2021-04-07 00:00:32
【问题描述】:
我想在 swift 中使用循环将项目附加到数组中。
我的代码如下所示,我看到了这个错误:
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
}
}
}
谁能告诉我这里的解决方案是什么?
【问题讨论】:
-
如果
response是字符串或数字或任何其他类型怎么办?dataResponse.value可以是任何东西。试试for item in response ?? [] {。 -
数据来自一个 api.. 我需要定义来自 API 的所有数据的类型吗?
-
我猜,这就是我们对 API 数据建模的原因。
-
我可以建议同时放弃 Alamofire 和 SwiftyJSON 以支持 URLSession 和 Codable 吗?这将摆脱很多包袱,并使您的模型类型更加明确和清晰。
-
您可以粘贴您的 json here,它将为您提供相应的结构和解码代码。
标签: ios swift for-in-loop