Reputation: 73
I am stuck with this guy [ : []]. As you can see, currently inside function I am using [0] to access value, but with this type of solution I can only access first element of array. How can I access all values? I tried with for in loop, but couldn't solve it...
Thanks in advance!
func tripServices(tripId: String) {
networkManager.getBookedTripsDetails(endpoint: "/v1/bookings/\(tripId)", tripId: tripId) { [unowned self] (safeTripsDetails) in
DispatchQueue.main.async {
self.bookedTripDetails = self.createScreenData(from: safeTripsDetails!, singleTrip: self.singleTrip!)
self.tableView.reloadData()
}
}
}
func createScreenData(from data: [String: [BookingService]], singleTrip: BookedTripsForView) -> [DetailsAboutServiceForView] {
return data.map{ ( data) -> DetailsAboutServiceForView in
return DetailsAboutServiceForView(id: singleTrip.id,
destination: data.value[0].destination,
tripStatus: data.value[0].status,
tripStartTime: data.value[0].startDate,
serviceName: data.value[0].serviceName,
serviceId: data.value[0].serviceId)
}
}
Upvotes: 0
Views: 96
Reputation: 131418
If you have a dictionary of arrays, and you want your output to be a single array containing all of the arrays combined into one array of a different type, there are various ways you could do that.
Rather than trying to work out your data types, I banged out an example using simple structs:
//Source struct
struct Person {
let name: String
let age: Int
}
//Output struct
struct Employee {
let name: String
let age: Int
let salary: Int?
}
let dictOfArrays = ["key1": [Person(name: "Bob", age: 36),
Person(name: "Felecia", age: 27),
Person(name: "Armin", age: 19)],
"key2": [Person(name: "Janet", age: 57),
Person(name: "John", age: 12),
Person(name: "Karen", age: 43)]
]
//Create an empty array for the output
var output = [Employee]()
//Loop through the dictionaries
dictOfArrays.forEach { (_, values) in
values.forEach { person in
//Only those who are >=18 can be employees
if person.age >= 18 {
output.append( Employee(name: person.name, age: person.age, salary: nil))
}
}
}
//Logs the resulting array of Employee structs.
output.forEach { print($0) }
As pointed out by Alexander in his comment, you can do the above in one statement without creating an array var and appending to it using a combination of flatmap, filter, and map:
let output = dictOfArrays.flatMap { (_, values) in
values.filter { $0.age >= 18 }
.map { person in
Employee(name: person.name, age: person.age, salary: nil)
}
}
Upvotes: 2