我正在尝试从我的Firebase数据库中获取用户。我希望所有用户都出现在表视图上。我正在尝试创建一个字典来做到这一点,但不断收到此错误:
条件绑定的初始值设定项必须具有可选类型,而不是"布尔">
这是我的代码:
func fetchUser() {
Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] != nil {
let user = User()
user.setValuesForKeysWithDictionary(dictionary)
print(user.name!, user.email!)
}
print("User found")
print(snapshot)
}, withCancel: nil)
}
删除!= nil
,则具有可选类型
if let dictionary = snapshot.value as? [String: AnyObject] { ...
只需像这样修改代码
func fetchUser() {
Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else{ return }
let user = User()
user.setValuesForKeysWithDictionary(dictionary)
print(user.name!, user.email!)
}
print("User found")
print(snapshot)
}, withCancel: nil)
}
}