【发布时间】:2021-04-09 19:29:46
【问题描述】:
晚上好!
我试图在我的 swift iOS 应用程序中从 firebase 检索布尔值,但我遇到了一个愚蠢的问题。从我的快照中解包字符串效果很好,但布尔值是另一回事......我显然错过了一些(希望)简单的东西。代码如下:
for child in snapshot.children{
let key = (child as AnyObject).key as String
let shouldBeBool = (child as AnyObject).value as Bool
...
// Do Stuff with the values
}
我在 Let shouldBeBool 行上收到“表达式类型不明确,没有更多上下文”错误。
如果我将“as Bool”更改为“as String”,代码将编译,但一旦尝试将快照中的布尔值作为字符串读取,应用程序就会按预期崩溃。
我也试过这个,得到同样的错误:
for child in snapshot.children{
let key = (child as AnyObject).key as String
var shouldBeBool: Bool
shouldBeBool = (child as AnyObject).value as! Bool
...
// Do Stuff with the values
}
我不明白强制将其作为布尔值展开是多么模棱两可。 swift 有不同类型的布尔值吗?
希望我只是错过了一些愚蠢的事情。
感谢您的宝贵时间。
更新 接受的答案有效(谢谢!),还有一个额外的修改。工作代码如下。
for child in snapshot.children{
let key = (child as AnyObject).key as String
let b = (child as! DataSnapshot).value as! NSNumber // Note the double force unwrapping... bad practice?
let shouldBeBool = Bool(truncating: b)
...
// Do Stuff with shouldBeBool as a boolean and key as a string
}
【问题讨论】:
标签: json swift firebase firebase-realtime-database