Ios 在嵌套子对象中迭代。Firebase和Swift 3
以下是我的数据结构:Ios 在嵌套子对象中迭代。Firebase和Swift 3,ios,swift,firebase,Ios,Swift,Firebase,以下是我的数据结构: { "ItemData": { "Item": [ { "name": "Table", "measurement ": [ { "height": 30 }, { "width": 50 } ] } ] } } 我目前可以从Firebase获取所有数据,
{ "ItemData": {
"Item": [
{
"name": "Table",
"measurement ": [
{
"height": 30
},
{
"width": 50
}
]
}
]
}
}
我目前可以从Firebase获取所有数据,并能够在tableView上显示名称。我现在尝试获取嵌套在“测量”中的值,即“高度”和“宽度”。我已经看过了,但仍然不知道如何解决这个问题
这是我的项目类:
class Item {
var name: String!
var measurement: String!
var key: String
init(from snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as? [String: Any]
self.name = snapshotValue!["name"] as! String
self.measurement = snapshotValue?["measurement"] as! String
self.key = snapshot.key
}
}
这是我用来获取项目的函数。ItemManager是一个具有删除和添加项数组功能的类:
func fetchItem() {
let databaseRef = FIRDatabase.database().reference(withPath: "ItemData/Item/")
databaseRef.observe(.value, with: { snapshot in
ItemManager.shared.removeAll()
for item in snapshot.children {
guard let snapshot = item as? FIRDataSnapshot else { continue }
let item = Item(from: snapshot)
ItemManager.shared.additem(item)
print(snapshot)
}
self.tableView.reloadData()
})
}
如果可以,请帮助我:)如注释
测量字典数组中建议的,而不是字符串,因此如果您想从中获取高度和宽度,可以通过这种方式获取
class Item {
var name: String!
var heightMeasurement: String!
var widthMeasurement: String!
var key: String
init(from snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as? [String: Any]
self.name = snapshotValue!["name"] as! String
if let array = snapshotValue["measurement"] as? [[String:Any]],
let heightDic = array.first, let height = heightDic["height"],
let widthDic = array.last, let width = widthDic["width"] {
self.heightMeasurement = "\(height)"
self.widthMeasurement = "\(width)"
print(height, width)
}
else {
self.heightMeasurement = "" //set some default value
self.widthMeasurement = "" //set some default value
}
self.key = snapshot.key
}
}
注意:如果您的数组中有两个以上的对象,则要获取高度和宽度,您需要先订阅数组索引以获取字典,然后根据获取值访问其键。您得到了哪一个错误?您的第一个问题是度量值
是一个数组,所以它的所有元素都应该是相同的类型。但是,第一个元素用于高度
,下一个元素用于宽度
。如果您可以控制这一点,请将度量更改为字典。这样,就很容易检索到宽度
和高度
@PedroCastilho,我没有收到任何错误。我只是想得到测量值。@paulvs谢谢你的建议,我明白你的意思,但是我不知道如何实现这个改变。我只是把测量变成一本NSDictionary吗?谢谢你的Nirav,但它似乎并没有解决我的问题。您提供的代码不会打印任何内容。@请尝试将[[String:Int]]
替换为[[String:Any]]]
好的,它会工作并打印出值。但是我怎么称呼它呢,比如说UIlabel。我已经尝试过cell.heightLbl.text=item.measurement,但没有任何结果,并且非常确定这是错误的。很抱歉,我将更清楚地说明,我希望单独的标签显示度量值的数量(在本例中为2)。并显示这些值,以便height=“30”和width=“50”。@Chace检查编辑的答案,现在您可以将其设置为类似于cell.heightLbl.text=item.heightMeasurement
宽度的设置