和两个对象:
class Area: NSObject {
let itemRef:FIRDatabaseReference?
var id:String?
var name:String?
var cities : [City] = []
var collapsed: Bool
}
和
class City: NSObject {
var id:String?
var name:String?
init(_ id:String,_ name: String) {
self.id = id
self.name = name
}
override init(){
}
这是我的解析代码:
func makeData(){
let ref = FIRDatabase.database().reference().child("area")
ref.observe(.childAdded, with: {
(snapshot) in
if let dictionary = snapshot.value as? [String:AnyObject]{
print(dictionary)
}
})
}
我尝试将快照中的数据解析到我的阵列区域,但我不能 我怎么能这样做?
答案 0 :(得分:2)
你需要这样的东西:
(这只是一个例子,你需要根据你的情况进行调整)
let ref = FIRDatabase.database().reference().child("area")
ref.observe(.childAdded, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: Any] else {
return
}
// Create the area object
let area = Area()
// Add id in the area
area.id = snapshot.key
// Init cities
area.cities = [City]()
if let cities = dictionary["cities"] as? [String: Any] {
for (key, value) in cities {
guard let cityName = value["name"] as? String else {
continue
}
// Create the city object
let city = City(key, cityName)
// Add city to cities in the area
area.cities.append(city)
}
}
if let name = dictionary["name"] as? String {
// Add name in the area
area.name = name
}
// Use the area
})