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

Viewed 2716

I want to append items to an array using a loop in swift.

My code looks like the following and I am seeing this error:

For-in loop requires '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:

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?

1 Answers

The error here is that dataResponse.value is JSON so in order to use the value property you have to cast it.

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. I also suggest you to use Swift Codables in order to map your json responses. reference here: https://www.hackingwithswift.com/articles/119/codable-cheat-sheet

Related