Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...