2
我的数据库结构如下:火力地堡数据库 - 如何斯威夫特词典获取从多个子节点和存储子值
"routines": {
"users unique identifier": {
"routine unique identifier": {
"routine_name": "routine name",
"routine_create_date": "routine created date",
"exercises": {
"exercise name": {
"Sets": "number of sets"
}
}
}
}
}
当检索数据,我想每个routine
存储为一个对象加载在UITableView
。我使用的常规结构为:
struct Routine {
var routineName: String!
var routineExercisesAndSets: [String:Int]!
}
如何从这个检索值,使每个Routine
模型,我可以有Routine(routineName: "Legs", routineExercisesAndSets: ["Squats":4,"Lunges":4,"Calf Raises":4])
其中演习的字典是exercise name
:number of sets
。
我目前使用不同的结构,几乎可以得到我想要的结果通过:
let ref = FIRDatabase.database().reference().child("routines").child(userId)
var routineTemp = Routine()
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject] {
routineTemp.routineName = dictionary["routineName"] as! String
let enumerator = snapshot.childSnapshot(forPath: "exercises").children
var exercisesAndSets = [String:Int]()
while let item = enumerator.nextObject() as? FIRDataSnapshot {
exercisesAndSets[item.key] = item.value! as? Int
}
routineTemp.routineExercisesAndSets = exercisesAndSets
print(routineTemp)
}
} , withCancel: nil)