ios - 无法将 '__NSDictionaryM' (0x1f0c63860) 类型的值转换为 'NSString' (0x1f0c70290) Swift

标签 ios swift firebase firebase-realtime-database

我正在从 Firebase 数据库读取数据,然后按字母顺序排序。 我想读取 Scenario 树下的键,但不是其下的整个数据。 然后我想将键放入 gradePickerValues1 变量中。

Firebase 数据库树

    2
      Scenario
       Yeni Senaryo
         OffTime: "12:12"
         OnTime: "12:12"
       Yeni Senaryo2
         OffTime: "12:12"
         OnTime: "12:12"

主要事件

  var gradePickerValues1 : [String] = []

  @objc func getSenaryo(){
    let ref = Database
      .database()
      .reference()
      .child(self.chipFieldText.text!)
      .child("Scenario")

    ref.observe(.value) { (snapshot) in
      for group in snapshot.children {
        self.gradePickerValues1.append((group as AnyObject).key)
      }
    }
  }

最佳答案

而不是

let userDict = userSnap.value as! String

let userDict = userSnap.value as! [String: [String: String]]

因为您的“场景”包含一个结构为[名称:[时间:字符串]]的字典。

如果你想从这个字典中获取Yeni SenaryoOffTime的“12:12”,你可以这样做:

let value = userDict["Yeni Senaryo"]!["OffTime"]!

如果数据库结构比较复杂,您应该使用[String: Any]代替,并使用if let语法来执行可选的类型转换。

编辑:如果您只想读取“Yeni Senaryo”而不是下面的值,则 Firebase 根本不可能实现这一点。

参见Best practices for data structure :

Avoid nesting data

Because the Firebase Realtime Database allows nesting data up to 32 levels deep, you might be tempted to think that this should be the default structure. However, when you fetch data at a location in your database, you also retrieve all of its child nodes. In addition, when you grant someone read or write access at a node in your database, you also grant them access to all data under that node. Therefore, in practice, it's best to keep your data structure as flat as possible.

无论如何,如果您不需要嵌套值而只需要名称,则可以这样做

let userDict = userSnap.value as! [String: Any]
let userNames = Array(userDict.keys)

并且名称数组作为String将存储在userNames中。

编辑2: 不要将 group 类型转换为 AnyObjectAnyObject.key 不是您想要的 key

for group in snapshot.children {
  guard let value = value as? DataSnapshot else { continue }
  self.gradePickerValues1.append(value.key)
}

关于ios - 无法将 '__NSDictionaryM' (0x1f0c63860) 类型的值转换为 'NSString' (0x1f0c70290) Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57153347/

相关文章:

javascript - 使用 startAt 和 endAt 的 Firebase 结果范围

ios - 随着 View 的变化实时更新状态栏文本颜色

ios - AFNetworking V 2 是否支持非流式多部分后台上传任务?

ios - 如何使用 Swift 在 Tableview Cell 中添加 UITableview

ios - 发送通用推送通知 - Xcode

iOS Swift - 从选定的 TableView 单元格获取背景颜色

ios - 所以。我试图让我的文本字段下的字符数在屏幕上增加,但它没有增加

firebase - Firestore 规则无需身份验证即可写入/更新特定字段

ios - Firebase iOS - 更改 App ID 前缀是否会影响用户

ios - 如何在已呈现的 Controller 上呈现新 Controller