Ios 如何在Firebase快照的控制流中使用Nil?(Swift)
我试图检查一个节点上是否存在一个键/值(TestKey/TestValue),它是否执行a操作,是否执行B操作 我在StackOverflow上发现了类似的线程,但没有一个解决方案适合我: 我已经建立了一个数据库,其中已经插入了TestKey/TestValue密钥对。 这是我的密码:Ios 如何在Firebase快照的控制流中使用Nil?(Swift),ios,swift,firebase,firebase-realtime-database,Ios,Swift,Firebase,Firebase Realtime Database,我试图检查一个节点上是否存在一个键/值(TestKey/TestValue),它是否执行a操作,是否执行B操作 我在StackOverflow上发现了类似的线程,但没有一个解决方案适合我: 我已经建立了一个数据库,其中已经插入了TestKey/TestValue密钥对。 这是我的密码: var ref: FIRDatabaseReference! ref = FIRDatabase.database().reference() ref.observeSingleEventOfT
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
ref.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
//A print test to see stored value before control flow
print(snapshot.value!["TestKey"]) //returns TestValue
print(snapshot.value!["NilKey"]) //returns nil
// I change the value from TestKey <-> NilKey here to test the control flow
if snapshot.value!["TestKey"] != nil {
print("Exists currently")
} else {
print("Does not exist currently")
}
}) { (error) in
print(error.localizedDescription)
}
var ref:FIRDatabaseReference!
ref=FIRDatabase.database().reference()
ref.observeSingleEventOfType(.Value,带块:{(快照)在
//在控制流之前查看存储值的打印测试
打印(snapshot.value![“TestKey”])//返回TestValue
打印(snapshot.value![“NilKey”])//返回nil
//我在这里更改TestKey NilKey的值来测试控制流
如果snapshot.value![“TestKey”]!=nil{
打印(“当前存在”)
}否则{
打印(“当前不存在”)
}
}){(错误)在
打印(错误。本地化描述)
}
问题是,即使打印测试显示结果为零,也只执行“A”
我尝试了用==nil反转操作,还尝试了“is NSNull”
我似乎无法使控制流正常工作。可能是以下原因之一,但我不确定:
我做错了什么?我如何才能让这个控制流工作?好吧,在做了很多修改之后,我找到了一个有效的解决方案,它确实是作为我之前链接的问题()的答案()发布的 使其工作的方法是在引用本身中输入TestKey,从snapshot.value(“TestKey”)中删除引用,然后使用“is Null” 以下是工作代码:
// Database already exists with "TestKey"/"TestValue"
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
// replace "TestKey" with another string to test for nil
ref.child("TestKey").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if snapshot.value is NSNull {
print("Does not exist currently")
} else {
print("Exists currently")
}
}) { (error) in
print(error.localizedDescription)
}
我很高兴我找到了这个解决方案,但如果有人想继续回答最初的问题,我很想知道为什么它不能以其他方式工作