You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase:Swift中snapshot.children.allObjects的Kotlin等价写法是什么?

Swift中snapshot.children.allObjects对应的Kotlin实现写法

在Firebase Realtime Database的Kotlin SDK里,DataSnapshot.children本身就是Iterable<DataSnapshot>类型,不需要像Swift那样通过allObjects转换数组,直接就能进行遍历、转集合等操作。以下是对应你Swift代码的Kotlin实现:

ref.addListenerForSingleValueEvent(object: ValueEventListener {

    override fun onDataChange(snapshot: DataSnapshot) {
        // 获取第一个子节点,对应Swift里的firstChild
        val firstChild = snapshot.children.firstOrNull()
        firstChild?.let {
            println(it.key)
        }

        // 将子节点转成List并反转,对应Swift里的arr和reversedArr
        val arr = snapshot.children.toList()
        val reversedArr = arr.reversed()

        // 遍历反转后的数组
        for (child in reversedArr) {
            val someId = child.key
            println(someId)
        }
    }

    override fun onCancelled(error: DatabaseError) { }
})

关键对应点说明:

  • Swift里的snapshot.children.allObjects.first as? DataSnapshot → Kotlin里用children.firstOrNull(),firstOrNull()会返回null而不是抛出异常,更符合Kotlin的空安全规范。
  • Swift里的snapshot.children.allObjects as! [DataSnapshot] → Kotlin里直接调用children.toList()就能得到List<DataSnapshot>。
  • 数组反转操作reversed()在Kotlin里直接对List调用即可,用法和Swift一致。

内容的提问来源于stack exchange,提问作者Lance Samaria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 03:42:05