【问题标题】:For-in loop requires 'JSON?' to conform to 'Sequence'; did you mean to unwrap optional?For-in 循环需要“JSON?”符合“顺序”;你的意思是解开可选的吗?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 2016-07-11
    • 2023-01-08
    • 2010-09-21
    • 2016-11-27
    相关资源
    最近更新 更多