首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >For-in循环需要“JSON?”若要符合“序列”,您是指可选地展开吗?

For-in循环需要“JSON?”若要符合“序列”,您是指可选地展开吗?
EN

Stack Overflow用户
提问于 2020-12-30 13:24:04
回答 1查看 3K关注 0票数 2

我想在want中使用循环将项附加到数组中。

我的代码如下所示,我看到了这个错误:

For-in循环需要'JSON?‘若要符合“序列”,您是指可选地展开吗?

在下面的代码中,我希望将每个电子邮件添加到类中定义的数组中:

代码语言:javascript
运行
复制
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
            }
        }
}

有人能告诉我解决办法是什么吗?

EN

回答 1

Stack Overflow用户

发布于 2020-12-30 13:34:16

这里的错误是dataResponse.value是JSON,所以为了使用value属性,您必须转换它。

所以您的代码应该是这样的:

代码语言:javascript
运行
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65507691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档