我正在尝试将isDisable附加到数组
到目前为止我所取得的成就:
func retrieving(){
Database.database().reference().child("ServingHours/\(choosenDate)").observeSingleEvent(of: .value, with: {(snapshot) in
if let eachDict = snapshot.value as? NSDictionary{
for each in eachDict{
print(each.value)
}
}
}, withCancel: {(Err) in
})
}
结果在控制台中:
{
isDisable = false;
numberOfRegistration = 0;
}
{
isDisable = false;
numberOfRegistration = 0;
}
{
isDisable = false;
numberOfRegistration = 0;
}
{
isDisable = false;
numberOfRegistration = 0;
}
据此,我不知道该怎么做才能从each.value
中获得特定值
答案 0 :(得分:0)
您正在检索特定日期对象,其中包含2个项目(isDisable和numberOfRegistration)。从Firebase检索它们时,您可以使用“ as?”将其强制转换为NSDictionary。
您的值似乎是字符串格式,因此,您可以使用以下方法从NSDictionary中检索它们:
let isDisabled = eachDict["isDisable"] as? String
let numberOfRegistration = eachDict["numberOfRegistration"] as? String
您还可以直接在Firebase中将您的值设置为Bool或Int,并且可以将检索到的对象类型转换为Bool(isDisable)和Int(numberOfRegistration)。但是看起来它们当前是字符串,所以您的代码会这样:
func retrieving(){
Database.database().reference().child("ServingHours/\(choosenDate)").observeSingleEvent(of: .value, with: {(snapshot) in
if let eachDict = snapshot.value as? NSDictionary{
let isDisabled = eachDict["isDisable"] as? String
let numberOfRegistration = eachDict["numberOfRegistration"] as? String
print(isDisabled)
print(numberOfRegistration)
}
}, withCancel: {(Err) in
})
}
此外,如果要直接检索值,则不需要使用NSDictionary。您可以直接将检索到的值转换为任何类型的对象。例如,假设您要直接检索“ isDisable”值:
func retrieving(){
Database.database().reference().child("ServingHours/\(choosenDate)").child("isDisable").observeSingleEvent(of: .value, with: {(snapshot) in
if let isDisable = snapshot.value as? String{
print(isDisable) }
查看Swift的Firebase官方文档: https://firebase.google.com/docs/database/ios/read-and-write
答案 1 :(得分:0)
您需要再次转换为字典(并且不要使用NSDictionary)
if let eachDict = snapshot.value as? [String: AnyObject]{
for each in eachDict {
if let innerDict = each as? [String: AnyObject] {
//innerDict now contains isDisable and numberOfRegistration
if let isDisable = innerDict["isDisable"] as? String
print(isDisable)
}
if let numberOfRegistration = innerDict["numberOfRegistration"] as? String {
print(numberOfRegistration)
}
}
}
}