0

I am using JSONDecoder to access JSON data through an API. Within this JSON Data are several [arrays]. I am running into a problem of accessing each instance that a key appears.

Here is the code:

var details = [Details]()
var production = [Production]()

struct Details: Codable {
    let title: String
    let poster_path: String?
    let id: Int?
    let production_companies: [Production]
}

struct Production: Codable {
    let name: String
}


let task = session.dataTask(with: request, completionHandler: { (dataOrNil, response, error) in
        if let data = dataOrNil {
            do { let details = try! JSONDecoder().decode(Details.self, from: data)

let production = details.production_companies
print(production)

 }
        }

    })

Here is what print(production) prints to the console:

[Film_Bee.DetailsView.Production(name: "Columbia Pictures"), Film_Bee.DetailsView.Production(name: "Marvel Entertainment"), Film_Bee.DetailsView.Production(name: "Sony Pictures")]

What I'm trying to do is access each name within the array. I know to access the first one I can use production.first?.name but if I am unsure how to access each one to place into a single label.

3
  • Do you want to add three companies' names into a single UIlabel or three UIlabel? Commented Oct 13, 2018 at 4:42
  • I'm wanting to put them into one label. Commented Oct 13, 2018 at 4:43
  • My answer to your previous question shows how to get all items in an array. Commented Oct 13, 2018 at 7:52

2 Answers 2

1

Prashant points already. I just additionally add a little bit which may help you.

I believe you know swift loop like for or forEach to see your string list

production.forEach { model in
    print(model.name)
}

For your problem, you need to join your string list. As you need to update UI, use DispatchQueue.

let productionList = production.map{$0.name}
let strings = productionList.joined(separator: " ") //use "\n" if you wish new line
print("stringList: \(strings)")
DispatchQueue.main.async() {  
 yourLabel.text = strings
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

let production = details.production_companies.map{$0.name}

What production_companies is Array. and you have to iterate over it using map and get its name that is simple to understand right ?

Not Related but don't use try! you should properly handle error use do try catch block

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.