我正在尝试从数据库中读取并将值放入一个字符串数组中。但是,当我尝试将值插入数组然后打印该数组时,应用程序崩溃了。
var pets: [String]?
override func viewDidLoad() {
super.viewDidLoad()
let userRef = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("pets")
userRef.observeSingleEvent(of: .value, with: { snapshot in
if let snap = snapshot.value as? Bool {
print("no values")
} else if let snap = snapshot.value as? NSDictionary {
for value in snap {
print(value.key as! String) // Prints out data in the database
self.pets?.append(value.key as! String)
}
print(self.pets!)
}
})
有谁知道为什么 print(value.key as!String)
打印出数据,但是当我打印出数组时,应用程序崩溃并显示 unexpectedly found nil while unwrapping an Optional值
?
最佳答案
您永远不会初始化宠物
。您将其声明为可选但从未为其分配值。为什么不将您的代码更改为以下内容:
var pets = [String]() // start with an empty array
override func viewDidLoad() {
super.viewDidLoad()
let userRef = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("pets")
userRef.observeSingleEvent(of: .value, with: { snapshot in
if let snap = snapshot.value as? Bool {
print("no values")
} else if let snap = snapshot.value as? NSDictionary {
for value in snap {
print(value.key as! String) // Prints out data in the database
self.pets.append(value.key as! String)
}
print(self.pets)
}
})
关于ios - 将数据库中的值读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41627583/