我正在尝试使用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()
}
}
任何帮助将不胜感激!预先感谢!
答案 0 :(得分:3)
您一次执行所有此功能,而无需等待首先实际获取数据:
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()
}