[英]How to set a variable inside closure using Swift 5 and use it outside closure
我正在尝试使用 Swift 在闭包内设置一个变量。 然后我想检索闭包之外的值以进行进一步处理。 我似乎不能这样做。 有什么办法可以做到吗? 我已经尝试了下面的代码。 我已经评论了我真正希望执行这些操作的部分。
class AttendanceDetailTVC: UITableViewController {
var TPNumber = ""
var Module = ""
var AID = ""
var intake = ""
@IBOutlet var tblDetail: UITableView!
var detailList = [DetailModel]()
var ref = Database.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
tblDetail.delegate = self
tblDetail.dataSource = self
ref.child("Student").child(TPNumber).child("Intake").observeSingleEvent(of: .value, with: {(snapshot) in
self.intake = (snapshot.value as? String)!
self.detailList.removeAll()
})
ref.child("Record").observe(.value) { (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let value = child.key
self.ref.child("Attendance").child(value).child("Intake").observe(.value, with: { (snapshot) in
for child1 in snapshot.children.allObjects as! [DataSnapshot] {
let value1 = child1.key
self.ref.child("Attendance").child(value).child("Intake").child(value1).observe(.value, with: { (snapshot) in
if let value2 = snapshot.value as? String {
if (self.intake == value2) {
self.AID = value //This is where I set the value
}
}
})
}
})
}
let det = DetailModel(AID: self.AID as String?) //This is where I want to use the value
self.detailList.append(det)
self.tblDetail.reloadData()
}
}
任何帮助,将不胜感激! 提前致谢!
您正在一次执行此 function,而无需等待首先实际检索数据:
override func viewDidLoad() {
super.viewDidLoad()
tblDetail.delegate = self
tblDetail.dataSource = self
ref.child("Record").observe(.value) { (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let value = child.key
self.ref.child("Attendance").child(value).child("Intake").observe(.value, with: { (snapshot) in
for child1 in snapshot.children.allObjects as! [DataSnapshot] {
let value1 = child1.key
self.ref.child("Attendance").child(value).child("Intake").child(value1).observe(.value, with: { (snapshot) in
if let value2 = snapshot.value as? String {
if (self.intake == value2) {
self.AID = value //This is where I set the value
self.reloadTable()
}
}
})
}
})
}
}
}
func reloadTable() {
let det = DetailModel(AID: self.AID) //This is where I wanna retrieve the value
self.detailList.append(det)
self.tblDetail.reloadData()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.