I wrote a piece of code that creates an array of objects based on the array of dictionaries. The problem is that my solution uses multiple loops imperatively.
Let's consider the following case. There is a class called Drug
:
class Drug {
var name:String
var dosage:[(dose:String,time:String)]
init(name:String){
self.name = name
self.dosage = []
}
}
I obtain the data as an array of dictionaries:
var array = [["drugName":"Amotaks", "time":"17.00", "dose":"5"], ["drugName":"Amotaks", "time":"18.00", "dose":"5"], ["drugName":"Amotaks", "time":"18.00", "dose":"5"], ["drugName":"Amotaks", "time":"17.00", "dose":"5"], ["drugName":"Claritin", "time":"17.00", "dose":"5"], ["drugName":"Claritin", "time":"18.00", "dose":"5"]]
Now is the tricky part. What is the best way to turn this data into an array of Drug
objects? I am not happy with my solution because it uses nested loops and additional helper arrays thus it's very inefficient.
The purpose is to create objects without repeating their names and provide each object with an dosage array which consist of (dose, time) tuples):
var DrugArray:[Drug] = []
var drugs:[String] = []
for i in array
{
if contains(drugs, i["drugName"]! as String){
continue
}
else{
drugs.append(i["drugName"]!)
DrugArray.append(Drug(name: i["drugName"]!))
}
}
for a in DrugArray{
for i in array {
if i["drugName"]! == a.name
{
a.dosage.append(dose: i["dose"]!, time: i["time"]!)
}
}}
I believe there is a better way to do that, probably in a few lines of code. I tried to figure out something with basic FP functions such as map or filter but I end up with nothing.
How can I perform the operation in an elegant way (probably using more advanced functional programming)?