ios - For-in 循环需要 'JSON?' 才能符合 'Sequence' ;你的意思是打开可选的吗?

标签 ios swift for-in-loop

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

我的代码如下所示,我看到此错误:

For-in loop requires 'JSON?' to conform to 'Sequence'; did you mean to unwrap optional?

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

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
            }
        }
}

我将其转换为字典,因为 JSON 响应大多数时候都是字典。我还建议您使用 Swift Codables 来映射您的 json 响应。引用这里:https://www.hackingwithswift.com/articles/119/codable-cheat-sheet

关于ios - For-in 循环需要 'JSON?' 才能符合 'Sequence' ;你的意思是打开可选的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65507691/

相关文章:

ios - UISplitViewController 中的 ActionSheet 在纵向模式下的行为不同于横向模式

iOS:UIView 外的实心边框

swift - 如何快速迭代 NSArrayController 内容?

ios - For-in 循环要求 '[UserVehicles]?' 符合 'Sequence' ;你的意思是解开可选的吗? swift

javascript - 在 iOS/Android 上运行的 Node.js 服务器

ios - 如何使用 MPMusicPlayerController 从特定索引播放 MPMediaItemCollection?

ios - 如何在 Swift 的 collectionView 中传递 indexPath 行数据

ios - type() 不符合协议(protocol)anyobject

ios - Xcode UITabBarController : Make Two tabs point to same ViewController

javascript - 未捕获的类型错误 : items is not iterable